diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 435ceac24c9b..4068d0273d92 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,175 +1,180 @@ { - "packages/google-ai-generativelanguage": "0.5.3", - "packages/google-analytics-admin": "0.22.6", - "packages/google-analytics-data": "0.18.6", - "packages/google-apps-meet": "0.1.5", - "packages/google-apps-script-type": "0.3.7", - "packages/google-area120-tables": "0.11.8", - "packages/google-cloud-access-approval": "1.13.2", - "packages/google-cloud-advisorynotifications": "0.3.6", - "packages/google-cloud-alloydb": "0.3.9", - "packages/google-cloud-alloydb-connectors": "0.1.3", - "packages/google-cloud-api-gateway": "1.9.2", - "packages/google-cloud-api-keys": "0.5.8", - "packages/google-cloud-apigee-connect": "1.9.2", - "packages/google-cloud-apigee-registry": "0.6.8", - "packages/google-cloud-appengine-admin": "1.11.2", - "packages/google-cloud-appengine-logging": "1.4.2", - "packages/google-cloud-artifact-registry": "1.11.2", - "packages/google-cloud-asset": "3.24.2", - "packages/google-cloud-assured-workloads": "1.12.2", - "packages/google-cloud-automl": "2.13.2", - "packages/google-cloud-bare-metal-solution": "1.7.2", - "packages/google-cloud-batch": "0.17.12", - "packages/google-cloud-beyondcorp-appconnections": "0.4.8", - "packages/google-cloud-beyondcorp-appconnectors": "0.4.8", - "packages/google-cloud-beyondcorp-appgateways": "0.4.8", - "packages/google-cloud-beyondcorp-clientconnectorservices": "0.4.8", - "packages/google-cloud-beyondcorp-clientgateways": "0.4.7", - "packages/google-cloud-bigquery-analyticshub": "0.4.7", - "packages/google-cloud-bigquery-biglake": "0.4.6", - "packages/google-cloud-bigquery-connection": "1.15.2", - "packages/google-cloud-bigquery-data-exchange": "0.5.10", - "packages/google-cloud-bigquery-datapolicies": "0.6.5", - "packages/google-cloud-bigquery-datatransfer": "3.15.0", - "packages/google-cloud-bigquery-logging": "1.4.2", - "packages/google-cloud-bigquery-migration": "0.11.6", - "packages/google-cloud-bigquery-reservation": "1.13.2", - "packages/google-cloud-billing": "1.13.2", - "packages/google-cloud-billing-budgets": "1.14.2", - "packages/google-cloud-binary-authorization": "1.10.2", - "packages/google-cloud-build": "3.23.2", - "packages/google-cloud-certificate-manager": "1.6.2", - "packages/google-cloud-channel": "1.18.2", - "packages/google-cloud-cloudquotas": "0.1.3", - "packages/google-cloud-commerce-consumer-procurement": "0.1.4", - "packages/google-cloud-common": "1.3.2", - "packages/google-cloud-compute": "1.17.0", - "packages/google-cloud-confidentialcomputing": "0.4.6", - "packages/google-cloud-config": "0.1.6", - "packages/google-cloud-contact-center-insights": "1.17.2", - "packages/google-cloud-container": "2.41.0", - "packages/google-cloud-containeranalysis": "2.14.2", - "packages/google-cloud-contentwarehouse": "0.7.6", - "packages/google-cloud-data-fusion": "1.10.2", - "packages/google-cloud-data-qna": "0.10.8", - "packages/google-cloud-datacatalog": "3.18.2", - "packages/google-cloud-datacatalog-lineage": "0.3.5", - "packages/google-cloud-dataflow-client": "0.8.9", - "packages/google-cloud-dataform": "0.5.8", - "packages/google-cloud-datalabeling": "1.10.2", - "packages/google-cloud-dataplex": "1.12.2", - "packages/google-cloud-dataproc": "5.9.2", - "packages/google-cloud-dataproc-metastore": "1.15.2", - "packages/google-cloud-datastream": "1.9.2", - "packages/google-cloud-deploy": "1.17.2", - "packages/google-cloud-dialogflow": "2.28.2", - "packages/google-cloud-dialogflow-cx": "1.32.0", - "packages/google-cloud-discoveryengine": "0.11.8", - "packages/google-cloud-dlp": "3.15.2", - "packages/google-cloud-dms": "1.9.2", - "packages/google-cloud-documentai": "2.24.0", - "packages/google-cloud-domains": "1.7.2", - "packages/google-cloud-edgecontainer": "0.5.7", - "packages/google-cloud-edgenetwork": "0.1.5", - "packages/google-cloud-enterpriseknowledgegraph": "0.3.8", - "packages/google-cloud-essential-contacts": "1.7.2", - "packages/google-cloud-eventarc": "1.11.2", - "packages/google-cloud-eventarc-publishing": "0.6.8", - "packages/google-cloud-filestore": "1.9.2", - "packages/google-cloud-functions": "1.16.2", - "packages/google-cloud-gke-backup": "0.5.6", - "packages/google-cloud-gke-connect-gateway": "0.8.8", - "packages/google-cloud-gke-hub": "1.13.0", - "packages/google-cloud-gke-multicloud": "0.6.8", - "packages/google-cloud-gsuiteaddons": "0.3.7", - "packages/google-cloud-iam": "2.14.2", - "packages/google-cloud-iam-logging": "1.3.2", - "packages/google-cloud-iap": "1.13.2", - "packages/google-cloud-ids": "1.7.2", - "packages/google-cloud-kms": "2.21.2", - "packages/google-cloud-kms-inventory": "0.2.5", - "packages/google-cloud-language": "2.13.2", - "packages/google-cloud-life-sciences": "0.9.8", - "packages/google-cloud-managed-identities": "1.9.2", - "packages/google-cloud-media-translation": "0.11.8", - "packages/google-cloud-memcache": "1.9.2", - "packages/google-cloud-migrationcenter": "0.1.6", - "packages/google-cloud-monitoring": "2.19.2", - "packages/google-cloud-monitoring-dashboards": "2.15.0", - "packages/google-cloud-monitoring-metrics-scopes": "1.6.2", - "packages/google-cloud-netapp": "0.3.6", - "packages/google-cloud-network-connectivity": "2.4.2", - "packages/google-cloud-network-management": "1.13.2", - "packages/google-cloud-network-security": "0.9.8", - "packages/google-cloud-network-services": "0.5.8", - "packages/google-cloud-notebooks": "1.10.2", - "packages/google-cloud-optimization": "1.8.2", - "packages/google-cloud-orchestration-airflow": "1.12.0", - "packages/google-cloud-os-config": "1.17.2", - "packages/google-cloud-os-login": "2.14.2", - "packages/google-cloud-phishing-protection": "1.11.2", - "packages/google-cloud-policy-troubleshooter": "1.11.2", - "packages/google-cloud-policysimulator": "0.1.5", - "packages/google-cloud-policytroubleshooter-iam": "0.1.4", - "packages/google-cloud-private-ca": "1.10.2", - "packages/google-cloud-private-catalog": "0.9.8", - "packages/google-cloud-public-ca": "0.3.8", - "packages/google-cloud-rapidmigrationassessment": "0.1.6", - "packages/google-cloud-recaptcha-enterprise": "1.18.0", - "packages/google-cloud-recommendations-ai": "0.10.9", - "packages/google-cloud-recommender": "2.15.2", - "packages/google-cloud-redis": "2.15.2", - "packages/google-cloud-redis-cluster": "0.1.4", - "packages/google-cloud-resource-manager": "1.12.2", - "packages/google-cloud-resource-settings": "1.9.2", - "packages/google-cloud-retail": "1.20.0", - "packages/google-cloud-run": "0.10.4", - "packages/google-cloud-scheduler": "2.13.2", - "packages/google-cloud-secret-manager": "2.18.2", - "packages/google-cloud-securesourcemanager": "0.1.4", - "packages/google-cloud-securitycenter": "1.27.0", - "packages/google-cloud-securitycentermanagement": "0.1.6", - "packages/google-cloud-service-control": "1.12.0", - "packages/google-cloud-service-directory": "1.11.2", - "packages/google-cloud-service-management": "1.8.2", - "packages/google-cloud-service-usage": "1.10.2", - "packages/google-cloud-servicehealth": "0.1.3", - "packages/google-cloud-shell": "1.9.2", - "packages/google-cloud-source-context": "1.5.2", - "packages/google-cloud-speech": "2.25.0", - "packages/google-cloud-storage-transfer": "1.11.2", - "packages/google-cloud-storageinsights": "0.1.7", - "packages/google-cloud-support": "0.1.6", - "packages/google-cloud-talent": "2.13.2", - "packages/google-cloud-tasks": "2.16.2", - "packages/google-cloud-telcoautomation": "0.2.2", - "packages/google-cloud-texttospeech": "2.16.2", - "packages/google-cloud-tpu": "1.18.2", - "packages/google-cloud-trace": "1.13.2", - "packages/google-cloud-translate": "3.15.2", - "packages/google-cloud-video-live-stream": "1.7.2", - "packages/google-cloud-video-stitcher": "0.7.8", - "packages/google-cloud-video-transcoder": "1.12.2", - "packages/google-cloud-videointelligence": "2.13.2", - "packages/google-cloud-vision": "3.7.1", - "packages/google-cloud-vm-migration": "1.8.2", - "packages/google-cloud-vmwareengine": "1.4.2", - "packages/google-cloud-vpc-access": "1.10.2", - "packages/google-cloud-webrisk": "1.14.2", - "packages/google-cloud-websecurityscanner": "1.14.2", - "packages/google-cloud-workflows": "1.14.2", - "packages/google-cloud-workstations": "0.5.5", - "packages/google-geo-type": "0.3.6", - "packages/google-maps-addressvalidation": "0.3.10", - "packages/google-maps-fleetengine": "0.1.8", - "packages/google-maps-fleetengine-delivery": "0.1.6", - "packages/google-maps-mapsplatformdatasets": "0.3.6", - "packages/google-maps-places": "0.1.9", - "packages/google-maps-routing": "0.6.6", - "packages/google-shopping-css": "0.1.3", - "packages/google-shopping-merchant-inventories": "0.1.4", - "packages/google-shopping-merchant-reports": "0.1.4", - "packages/google-shopping-type": "0.1.3", - "packages/grafeas": "1.9.2" + "packages/google-ai-generativelanguage": "0.5.4", + "packages/google-analytics-admin": "0.22.7", + "packages/google-analytics-data": "0.18.7", + "packages/google-apps-card": "0.1.1", + "packages/google-apps-chat": "0.1.0", + "packages/google-apps-events-subscriptions": "0.0.0", + "packages/google-apps-meet": "0.1.6", + "packages/google-apps-script-type": "0.3.8", + "packages/google-area120-tables": "0.11.9", + "packages/google-cloud-access-approval": "1.13.3", + "packages/google-cloud-advisorynotifications": "0.3.7", + "packages/google-cloud-alloydb": "0.3.10", + "packages/google-cloud-alloydb-connectors": "0.1.4", + "packages/google-cloud-api-gateway": "1.9.3", + "packages/google-cloud-api-keys": "0.5.9", + "packages/google-cloud-apigee-connect": "1.9.3", + "packages/google-cloud-apigee-registry": "0.6.9", + "packages/google-cloud-appengine-admin": "1.11.3", + "packages/google-cloud-appengine-logging": "1.4.3", + "packages/google-cloud-artifact-registry": "1.11.3", + "packages/google-cloud-asset": "3.24.3", + "packages/google-cloud-assured-workloads": "1.12.3", + "packages/google-cloud-automl": "2.13.3", + "packages/google-cloud-bare-metal-solution": "1.7.3", + "packages/google-cloud-batch": "0.17.14", + "packages/google-cloud-beyondcorp-appconnections": "0.4.9", + "packages/google-cloud-beyondcorp-appconnectors": "0.4.9", + "packages/google-cloud-beyondcorp-appgateways": "0.4.9", + "packages/google-cloud-beyondcorp-clientconnectorservices": "0.4.9", + "packages/google-cloud-beyondcorp-clientgateways": "0.4.8", + "packages/google-cloud-bigquery-analyticshub": "0.4.8", + "packages/google-cloud-bigquery-biglake": "0.4.7", + "packages/google-cloud-bigquery-connection": "1.15.3", + "packages/google-cloud-bigquery-data-exchange": "0.5.11", + "packages/google-cloud-bigquery-datapolicies": "0.6.6", + "packages/google-cloud-bigquery-datatransfer": "3.15.1", + "packages/google-cloud-bigquery-logging": "1.4.3", + "packages/google-cloud-bigquery-migration": "0.11.7", + "packages/google-cloud-bigquery-reservation": "1.13.3", + "packages/google-cloud-billing": "1.13.3", + "packages/google-cloud-billing-budgets": "1.14.3", + "packages/google-cloud-binary-authorization": "1.10.3", + "packages/google-cloud-build": "3.23.3", + "packages/google-cloud-certificate-manager": "1.6.3", + "packages/google-cloud-channel": "1.18.3", + "packages/google-cloud-cloudcontrolspartner": "0.1.0", + "packages/google-cloud-cloudquotas": "0.1.4", + "packages/google-cloud-commerce-consumer-procurement": "0.1.5", + "packages/google-cloud-common": "1.3.3", + "packages/google-cloud-compute": "1.18.0", + "packages/google-cloud-confidentialcomputing": "0.4.7", + "packages/google-cloud-config": "0.1.7", + "packages/google-cloud-contact-center-insights": "1.17.3", + "packages/google-cloud-container": "2.42.0", + "packages/google-cloud-containeranalysis": "2.14.3", + "packages/google-cloud-contentwarehouse": "0.7.7", + "packages/google-cloud-data-fusion": "1.10.3", + "packages/google-cloud-data-qna": "0.10.9", + "packages/google-cloud-datacatalog": "3.18.3", + "packages/google-cloud-datacatalog-lineage": "0.3.6", + "packages/google-cloud-dataflow-client": "0.8.10", + "packages/google-cloud-dataform": "0.5.9", + "packages/google-cloud-datalabeling": "1.10.3", + "packages/google-cloud-dataplex": "1.12.3", + "packages/google-cloud-dataproc": "5.9.3", + "packages/google-cloud-dataproc-metastore": "1.15.3", + "packages/google-cloud-datastream": "1.9.3", + "packages/google-cloud-deploy": "1.17.3", + "packages/google-cloud-dialogflow": "2.28.3", + "packages/google-cloud-dialogflow-cx": "1.32.1", + "packages/google-cloud-discoveryengine": "0.11.9", + "packages/google-cloud-dlp": "3.15.3", + "packages/google-cloud-dms": "1.9.3", + "packages/google-cloud-documentai": "2.24.1", + "packages/google-cloud-domains": "1.7.3", + "packages/google-cloud-edgecontainer": "0.5.8", + "packages/google-cloud-edgenetwork": "0.1.6", + "packages/google-cloud-enterpriseknowledgegraph": "0.3.9", + "packages/google-cloud-essential-contacts": "1.7.3", + "packages/google-cloud-eventarc": "1.11.3", + "packages/google-cloud-eventarc-publishing": "0.6.9", + "packages/google-cloud-filestore": "1.9.3", + "packages/google-cloud-functions": "1.16.3", + "packages/google-cloud-gke-backup": "0.5.7", + "packages/google-cloud-gke-connect-gateway": "0.8.9", + "packages/google-cloud-gke-hub": "1.13.1", + "packages/google-cloud-gke-multicloud": "0.6.9", + "packages/google-cloud-gsuiteaddons": "0.3.8", + "packages/google-cloud-iam": "2.14.3", + "packages/google-cloud-iam-logging": "1.3.3", + "packages/google-cloud-iap": "1.13.3", + "packages/google-cloud-ids": "1.7.3", + "packages/google-cloud-kms": "2.21.3", + "packages/google-cloud-kms-inventory": "0.2.6", + "packages/google-cloud-language": "2.13.3", + "packages/google-cloud-life-sciences": "0.9.9", + "packages/google-cloud-managed-identities": "1.9.3", + "packages/google-cloud-media-translation": "0.11.9", + "packages/google-cloud-memcache": "1.9.3", + "packages/google-cloud-migrationcenter": "0.1.7", + "packages/google-cloud-monitoring": "2.19.3", + "packages/google-cloud-monitoring-dashboards": "2.15.1", + "packages/google-cloud-monitoring-metrics-scopes": "1.6.3", + "packages/google-cloud-netapp": "0.3.7", + "packages/google-cloud-network-connectivity": "2.4.3", + "packages/google-cloud-network-management": "1.13.3", + "packages/google-cloud-network-security": "0.9.9", + "packages/google-cloud-network-services": "0.5.9", + "packages/google-cloud-notebooks": "1.10.3", + "packages/google-cloud-optimization": "1.8.3", + "packages/google-cloud-orchestration-airflow": "1.12.1", + "packages/google-cloud-os-config": "1.17.3", + "packages/google-cloud-os-login": "2.14.3", + "packages/google-cloud-parallelstore": "0.1.1", + "packages/google-cloud-phishing-protection": "1.11.3", + "packages/google-cloud-policy-troubleshooter": "1.11.3", + "packages/google-cloud-policysimulator": "0.1.6", + "packages/google-cloud-policytroubleshooter-iam": "0.1.5", + "packages/google-cloud-private-ca": "1.10.3", + "packages/google-cloud-private-catalog": "0.9.9", + "packages/google-cloud-public-ca": "0.3.9", + "packages/google-cloud-rapidmigrationassessment": "0.1.7", + "packages/google-cloud-recaptcha-enterprise": "1.18.1", + "packages/google-cloud-recommendations-ai": "0.10.10", + "packages/google-cloud-recommender": "2.15.3", + "packages/google-cloud-redis": "2.15.3", + "packages/google-cloud-redis-cluster": "0.1.5", + "packages/google-cloud-resource-manager": "1.12.3", + "packages/google-cloud-resource-settings": "1.9.3", + "packages/google-cloud-retail": "1.20.1", + "packages/google-cloud-run": "0.10.5", + "packages/google-cloud-scheduler": "2.13.3", + "packages/google-cloud-secret-manager": "2.18.3", + "packages/google-cloud-securesourcemanager": "0.1.5", + "packages/google-cloud-securitycenter": "1.28.0", + "packages/google-cloud-securitycentermanagement": "0.1.7", + "packages/google-cloud-service-control": "1.12.1", + "packages/google-cloud-service-directory": "1.11.3", + "packages/google-cloud-service-management": "1.8.3", + "packages/google-cloud-service-usage": "1.10.3", + "packages/google-cloud-servicehealth": "0.1.4", + "packages/google-cloud-shell": "1.9.3", + "packages/google-cloud-source-context": "1.5.3", + "packages/google-cloud-speech": "2.25.1", + "packages/google-cloud-storage-transfer": "1.11.3", + "packages/google-cloud-storageinsights": "0.1.8", + "packages/google-cloud-support": "0.1.7", + "packages/google-cloud-talent": "2.13.3", + "packages/google-cloud-tasks": "2.16.3", + "packages/google-cloud-telcoautomation": "0.2.3", + "packages/google-cloud-texttospeech": "2.16.3", + "packages/google-cloud-tpu": "1.18.3", + "packages/google-cloud-trace": "1.13.3", + "packages/google-cloud-translate": "3.15.3", + "packages/google-cloud-video-live-stream": "1.7.3", + "packages/google-cloud-video-stitcher": "0.7.9", + "packages/google-cloud-video-transcoder": "1.12.3", + "packages/google-cloud-videointelligence": "2.13.3", + "packages/google-cloud-vision": "3.7.2", + "packages/google-cloud-vm-migration": "1.8.3", + "packages/google-cloud-vmwareengine": "1.4.3", + "packages/google-cloud-vpc-access": "1.10.3", + "packages/google-cloud-webrisk": "1.14.3", + "packages/google-cloud-websecurityscanner": "1.14.3", + "packages/google-cloud-workflows": "1.14.3", + "packages/google-cloud-workstations": "0.5.6", + "packages/google-geo-type": "0.3.7", + "packages/google-maps-addressvalidation": "0.3.11", + "packages/google-maps-fleetengine": "0.1.9", + "packages/google-maps-fleetengine-delivery": "0.1.7", + "packages/google-maps-mapsplatformdatasets": "0.3.7", + "packages/google-maps-places": "0.1.10", + "packages/google-maps-routing": "0.6.7", + "packages/google-shopping-css": "0.1.4", + "packages/google-shopping-merchant-inventories": "0.1.5", + "packages/google-shopping-merchant-reports": "0.1.5", + "packages/google-shopping-type": "0.1.4", + "packages/grafeas": "1.9.3" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f3849bfe02a..2546938d6ac9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,177 +2,180 @@ Please refer to each API's `CHANGELOG.md` file under the `packages/` directory Changelogs ----- -- [google-ai-generativelanguage==0.5.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-ai-generativelanguage/CHANGELOG.md) -- [google-analytics-admin==0.22.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-analytics-admin/CHANGELOG.md) -- [google-analytics-data==0.18.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-analytics-data/CHANGELOG.md) -- [google-apps-meet==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-meet/CHANGELOG.md) -- [google-apps-script-type==0.3.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-script-type/CHANGELOG.md) -- [google-area120-tables==0.11.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-area120-tables/CHANGELOG.md) -- [google-cloud-access-approval==1.13.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-access-approval/CHANGELOG.md) -- [google-cloud-advisorynotifications==0.3.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-advisorynotifications/CHANGELOG.md) -- [google-cloud-alloydb-connectors==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-alloydb-connectors/CHANGELOG.md) -- [google-cloud-alloydb==0.3.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-alloydb/CHANGELOG.md) -- [google-cloud-api-gateway==1.9.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-api-gateway/CHANGELOG.md) -- [google-cloud-api-keys==0.5.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-api-keys/CHANGELOG.md) -- [google-cloud-apigee-connect==1.9.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apigee-connect/CHANGELOG.md) -- [google-cloud-apigee-registry==0.6.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apigee-registry/CHANGELOG.md) -- [google-cloud-appengine-admin==1.11.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-appengine-admin/CHANGELOG.md) -- [google-cloud-appengine-logging==1.4.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-appengine-logging/CHANGELOG.md) -- [google-cloud-artifact-registry==1.11.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-artifact-registry/CHANGELOG.md) -- [google-cloud-asset==3.24.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-asset/CHANGELOG.md) -- [google-cloud-assured-workloads==1.12.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-assured-workloads/CHANGELOG.md) -- [google-cloud-automl==2.13.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-automl/CHANGELOG.md) -- [google-cloud-bare-metal-solution==1.7.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bare-metal-solution/CHANGELOG.md) -- [google-cloud-batch==0.17.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-batch/CHANGELOG.md) -- [google-cloud-beyondcorp-appconnections==0.4.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appconnections/CHANGELOG.md) -- [google-cloud-beyondcorp-appconnectors==0.4.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appconnectors/CHANGELOG.md) -- [google-cloud-beyondcorp-appgateways==0.4.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appgateways/CHANGELOG.md) -- [google-cloud-beyondcorp-clientconnectorservices==0.4.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-clientconnectorservices/CHANGELOG.md) -- [google-cloud-beyondcorp-clientgateways==0.4.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-clientgateways/CHANGELOG.md) -- [google-cloud-bigquery-analyticshub==0.4.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-analyticshub/CHANGELOG.md) -- [google-cloud-bigquery-biglake==0.4.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-biglake/CHANGELOG.md) -- [google-cloud-bigquery-connection==1.15.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-connection/CHANGELOG.md) -- [google-cloud-bigquery-data-exchange==0.5.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-data-exchange/CHANGELOG.md) -- [google-cloud-bigquery-datapolicies==0.6.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-datapolicies/CHANGELOG.md) -- [google-cloud-bigquery-datatransfer==3.14.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-datatransfer/CHANGELOG.md) -- [google-cloud-bigquery-logging==1.4.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-logging/CHANGELOG.md) -- [google-cloud-bigquery-migration==0.11.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-migration/CHANGELOG.md) -- [google-cloud-bigquery-reservation==1.13.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-reservation/CHANGELOG.md) -- [google-cloud-billing-budgets==1.14.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-billing-budgets/CHANGELOG.md) -- [google-cloud-billing==1.13.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-billing/CHANGELOG.md) -- [google-cloud-binary-authorization==1.10.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-binary-authorization/CHANGELOG.md) -- [google-cloud-build==3.23.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-build/CHANGELOG.md) -- [google-cloud-certificate-manager==1.6.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-certificate-manager/CHANGELOG.md) -- [google-cloud-channel==1.18.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-channel/CHANGELOG.md) -- [google-cloud-cloudquotas==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-cloudquotas/CHANGELOG.md) -- [google-cloud-commerce-consumer-procurement==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-commerce-consumer-procurement/CHANGELOG.md) -- [google-cloud-common==1.3.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-common/CHANGELOG.md) -- [google-cloud-compute==1.16.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-compute/CHANGELOG.md) -- [google-cloud-confidentialcomputing==0.4.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-confidentialcomputing/CHANGELOG.md) -- [google-cloud-config==0.1.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-config/CHANGELOG.md) -- [google-cloud-contact-center-insights==1.17.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-contact-center-insights/CHANGELOG.md) -- [google-cloud-container==2.40.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-container/CHANGELOG.md) -- [google-cloud-containeranalysis==2.14.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-containeranalysis/CHANGELOG.md) -- [google-cloud-contentwarehouse==0.7.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-contentwarehouse/CHANGELOG.md) -- [google-cloud-data-fusion==1.10.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-data-fusion/CHANGELOG.md) -- [google-cloud-data-qna==0.10.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-data-qna/CHANGELOG.md) -- [google-cloud-datacatalog-lineage==0.3.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datacatalog-lineage/CHANGELOG.md) -- [google-cloud-datacatalog==3.18.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datacatalog/CHANGELOG.md) -- [google-cloud-dataflow-client==0.8.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataflow-client/CHANGELOG.md) -- [google-cloud-dataform==0.5.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataform/CHANGELOG.md) -- [google-cloud-datalabeling==1.10.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datalabeling/CHANGELOG.md) -- [google-cloud-dataplex==1.12.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataplex/CHANGELOG.md) -- [google-cloud-dataproc-metastore==1.15.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataproc-metastore/CHANGELOG.md) -- [google-cloud-dataproc==5.9.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataproc/CHANGELOG.md) -- [google-cloud-datastream==1.9.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datastream/CHANGELOG.md) -- [google-cloud-deploy==1.17.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-deploy/CHANGELOG.md) -- [google-cloud-dialogflow-cx==1.31.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dialogflow-cx/CHANGELOG.md) -- [google-cloud-dialogflow==2.28.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dialogflow/CHANGELOG.md) -- [google-cloud-discoveryengine==0.11.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-discoveryengine/CHANGELOG.md) -- [google-cloud-dlp==3.15.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dlp/CHANGELOG.md) -- [google-cloud-dms==1.9.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dms/CHANGELOG.md) -- [google-cloud-documentai==2.23.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-documentai/CHANGELOG.md) -- [google-cloud-domains==1.7.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-domains/CHANGELOG.md) -- [google-cloud-edgecontainer==0.5.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-edgecontainer/CHANGELOG.md) -- [google-cloud-edgenetwork==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-edgenetwork/CHANGELOG.md) -- [google-cloud-enterpriseknowledgegraph==0.3.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-enterpriseknowledgegraph/CHANGELOG.md) -- [google-cloud-essential-contacts==1.7.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-essential-contacts/CHANGELOG.md) -- [google-cloud-eventarc-publishing==0.6.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-eventarc-publishing/CHANGELOG.md) -- [google-cloud-eventarc==1.11.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-eventarc/CHANGELOG.md) -- [google-cloud-filestore==1.9.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-filestore/CHANGELOG.md) -- [google-cloud-functions==1.16.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-functions/CHANGELOG.md) -- [google-cloud-gke-backup==0.5.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-backup/CHANGELOG.md) -- [google-cloud-gke-connect-gateway==0.8.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-connect-gateway/CHANGELOG.md) -- [google-cloud-gke-hub==1.12.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-hub/CHANGELOG.md) -- [google-cloud-gke-multicloud==0.6.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-multicloud/CHANGELOG.md) -- [google-cloud-gsuiteaddons==0.3.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gsuiteaddons/CHANGELOG.md) -- [google-cloud-iam-logging==1.3.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iam-logging/CHANGELOG.md) -- [google-cloud-iam==2.14.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iam/CHANGELOG.md) -- [google-cloud-iap==1.13.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iap/CHANGELOG.md) -- [google-cloud-ids==1.7.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-ids/CHANGELOG.md) -- [google-cloud-kms-inventory==0.2.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-kms-inventory/CHANGELOG.md) -- [google-cloud-kms==2.21.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-kms/CHANGELOG.md) -- [google-cloud-language==2.13.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-language/CHANGELOG.md) -- [google-cloud-life-sciences==0.9.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-life-sciences/CHANGELOG.md) -- [google-cloud-managed-identities==1.9.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-managed-identities/CHANGELOG.md) -- [google-cloud-media-translation==0.11.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-media-translation/CHANGELOG.md) -- [google-cloud-memcache==1.9.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-memcache/CHANGELOG.md) -- [google-cloud-migrationcenter==0.1.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-migrationcenter/CHANGELOG.md) -- [google-cloud-monitoring-dashboards==2.14.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring-dashboards/CHANGELOG.md) -- [google-cloud-monitoring-metrics-scopes==1.6.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring-metrics-scopes/CHANGELOG.md) -- [google-cloud-monitoring==2.19.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring/CHANGELOG.md) -- [google-cloud-netapp==0.3.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-netapp/CHANGELOG.md) -- [google-cloud-network-connectivity==2.4.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-connectivity/CHANGELOG.md) -- [google-cloud-network-management==1.13.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-management/CHANGELOG.md) -- [google-cloud-network-security==0.9.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-security/CHANGELOG.md) -- [google-cloud-network-services==0.5.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-services/CHANGELOG.md) -- [google-cloud-notebooks==1.10.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-notebooks/CHANGELOG.md) -- [google-cloud-optimization==1.8.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-optimization/CHANGELOG.md) -- [google-cloud-orchestration-airflow==1.11.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-orchestration-airflow/CHANGELOG.md) -- [google-cloud-os-config==1.17.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-os-config/CHANGELOG.md) -- [google-cloud-os-login==2.14.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-os-login/CHANGELOG.md) -- [google-cloud-phishing-protection==1.11.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-phishing-protection/CHANGELOG.md) -- [google-cloud-policy-troubleshooter==1.11.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policy-troubleshooter/CHANGELOG.md) -- [google-cloud-policysimulator==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policysimulator/CHANGELOG.md) -- [google-cloud-policytroubleshooter-iam==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policytroubleshooter-iam/CHANGELOG.md) -- [google-cloud-private-ca==1.10.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-private-ca/CHANGELOG.md) -- [google-cloud-private-catalog==0.9.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-private-catalog/CHANGELOG.md) -- [google-cloud-public-ca==0.3.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-public-ca/CHANGELOG.md) -- [google-cloud-rapidmigrationassessment==0.1.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-rapidmigrationassessment/CHANGELOG.md) -- [google-cloud-recaptcha-enterprise==1.17.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recaptcha-enterprise/CHANGELOG.md) -- [google-cloud-recommendations-ai==0.10.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recommendations-ai/CHANGELOG.md) -- [google-cloud-recommender==2.15.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recommender/CHANGELOG.md) -- [google-cloud-redis-cluster==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-redis-cluster/CHANGELOG.md) -- [google-cloud-redis==2.15.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-redis/CHANGELOG.md) -- [google-cloud-resource-manager==1.12.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-resource-manager/CHANGELOG.md) -- [google-cloud-resource-settings==1.9.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-resource-settings/CHANGELOG.md) -- [google-cloud-retail==1.19.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-retail/CHANGELOG.md) -- [google-cloud-run==0.10.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-run/CHANGELOG.md) -- [google-cloud-scheduler==2.13.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-scheduler/CHANGELOG.md) -- [google-cloud-secret-manager==2.18.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-secret-manager/CHANGELOG.md) -- [google-cloud-securesourcemanager==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securesourcemanager/CHANGELOG.md) -- [google-cloud-securitycenter==1.26.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter/CHANGELOG.md) -- [google-cloud-securitycentermanagement==0.1.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycentermanagement/CHANGELOG.md) -- [google-cloud-service-control==1.11.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-control/CHANGELOG.md) -- [google-cloud-service-directory==1.11.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-directory/CHANGELOG.md) -- [google-cloud-service-management==1.8.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-management/CHANGELOG.md) -- [google-cloud-service-usage==1.10.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-usage/CHANGELOG.md) -- [google-cloud-servicehealth==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-servicehealth/CHANGELOG.md) -- [google-cloud-shell==1.9.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-shell/CHANGELOG.md) -- [google-cloud-source-context==1.5.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-source-context/CHANGELOG.md) -- [google-cloud-speech==2.24.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-speech/CHANGELOG.md) -- [google-cloud-storage-transfer==1.11.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storage-transfer/CHANGELOG.md) -- [google-cloud-storageinsights==0.1.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storageinsights/CHANGELOG.md) -- [google-cloud-support==0.1.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-support/CHANGELOG.md) -- [google-cloud-talent==2.13.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-talent/CHANGELOG.md) -- [google-cloud-tasks==2.16.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-tasks/CHANGELOG.md) -- [google-cloud-telcoautomation==0.2.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-telcoautomation/CHANGELOG.md) -- [google-cloud-texttospeech==2.16.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-texttospeech/CHANGELOG.md) -- [google-cloud-tpu==1.18.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-tpu/CHANGELOG.md) -- [google-cloud-trace==1.13.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-trace/CHANGELOG.md) -- [google-cloud-translate==3.15.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-translate/CHANGELOG.md) -- [google-cloud-video-live-stream==1.7.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-live-stream/CHANGELOG.md) -- [google-cloud-video-stitcher==0.7.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-stitcher/CHANGELOG.md) -- [google-cloud-video-transcoder==1.12.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-transcoder/CHANGELOG.md) -- [google-cloud-videointelligence==2.13.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-videointelligence/CHANGELOG.md) -- [google-cloud-vision==3.7.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vision/CHANGELOG.md) -- [google-cloud-vm-migration==1.8.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vm-migration/CHANGELOG.md) -- [google-cloud-vmwareengine==1.4.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vmwareengine/CHANGELOG.md) -- [google-cloud-vpc-access==1.10.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vpc-access/CHANGELOG.md) -- [google-cloud-webrisk==1.14.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-webrisk/CHANGELOG.md) -- [google-cloud-websecurityscanner==1.14.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-websecurityscanner/CHANGELOG.md) -- [google-cloud-workflows==1.14.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workflows/CHANGELOG.md) -- [google-cloud-workstations==0.5.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workstations/CHANGELOG.md) -- [google-geo-type==0.3.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-geo-type/CHANGELOG.md) -- [google-maps-addressvalidation==0.3.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-addressvalidation/CHANGELOG.md) -- [google-maps-fleetengine-delivery==0.1.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-fleetengine-delivery/CHANGELOG.md) -- [google-maps-fleetengine==0.1.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-fleetengine/CHANGELOG.md) -- [google-maps-mapsplatformdatasets==0.3.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-mapsplatformdatasets/CHANGELOG.md) -- [google-maps-places==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-places/CHANGELOG.md) -- [google-maps-routing==0.6.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-routing/CHANGELOG.md) -- [google-shopping-css==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-css/CHANGELOG.md) -- [google-shopping-merchant-inventories==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-inventories/CHANGELOG.md) -- [google-shopping-merchant-reports==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-reports/CHANGELOG.md) -- [google-shopping-type==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-type/CHANGELOG.md) -- [grafeas==1.9.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/grafeas/CHANGELOG.md) +- [google-ai-generativelanguage==0.5.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-ai-generativelanguage/CHANGELOG.md) +- [google-analytics-admin==0.22.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-analytics-admin/CHANGELOG.md) +- [google-analytics-data==0.18.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-analytics-data/CHANGELOG.md) +- [google-apps-card==0.1.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-card/CHANGELOG.md) +- [google-apps-chat==0.0.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-chat/CHANGELOG.md) +- [google-apps-meet==0.1.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-meet/CHANGELOG.md) +- [google-apps-script-type==0.3.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-script-type/CHANGELOG.md) +- [google-area120-tables==0.11.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-area120-tables/CHANGELOG.md) +- [google-cloud-access-approval==1.13.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-access-approval/CHANGELOG.md) +- [google-cloud-advisorynotifications==0.3.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-advisorynotifications/CHANGELOG.md) +- [google-cloud-alloydb-connectors==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-alloydb-connectors/CHANGELOG.md) +- [google-cloud-alloydb==0.3.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-alloydb/CHANGELOG.md) +- [google-cloud-api-gateway==1.9.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-api-gateway/CHANGELOG.md) +- [google-cloud-api-keys==0.5.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-api-keys/CHANGELOG.md) +- [google-cloud-apigee-connect==1.9.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apigee-connect/CHANGELOG.md) +- [google-cloud-apigee-registry==0.6.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apigee-registry/CHANGELOG.md) +- [google-cloud-appengine-admin==1.11.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-appengine-admin/CHANGELOG.md) +- [google-cloud-appengine-logging==1.4.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-appengine-logging/CHANGELOG.md) +- [google-cloud-artifact-registry==1.11.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-artifact-registry/CHANGELOG.md) +- [google-cloud-asset==3.24.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-asset/CHANGELOG.md) +- [google-cloud-assured-workloads==1.12.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-assured-workloads/CHANGELOG.md) +- [google-cloud-automl==2.13.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-automl/CHANGELOG.md) +- [google-cloud-bare-metal-solution==1.7.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bare-metal-solution/CHANGELOG.md) +- [google-cloud-batch==0.17.13](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-batch/CHANGELOG.md) +- [google-cloud-beyondcorp-appconnections==0.4.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appconnections/CHANGELOG.md) +- [google-cloud-beyondcorp-appconnectors==0.4.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appconnectors/CHANGELOG.md) +- [google-cloud-beyondcorp-appgateways==0.4.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appgateways/CHANGELOG.md) +- [google-cloud-beyondcorp-clientconnectorservices==0.4.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-clientconnectorservices/CHANGELOG.md) +- [google-cloud-beyondcorp-clientgateways==0.4.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-clientgateways/CHANGELOG.md) +- [google-cloud-bigquery-analyticshub==0.4.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-analyticshub/CHANGELOG.md) +- [google-cloud-bigquery-biglake==0.4.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-biglake/CHANGELOG.md) +- [google-cloud-bigquery-connection==1.15.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-connection/CHANGELOG.md) +- [google-cloud-bigquery-data-exchange==0.5.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-data-exchange/CHANGELOG.md) +- [google-cloud-bigquery-datapolicies==0.6.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-datapolicies/CHANGELOG.md) +- [google-cloud-bigquery-datatransfer==3.15.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-datatransfer/CHANGELOG.md) +- [google-cloud-bigquery-logging==1.4.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-logging/CHANGELOG.md) +- [google-cloud-bigquery-migration==0.11.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-migration/CHANGELOG.md) +- [google-cloud-bigquery-reservation==1.13.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-reservation/CHANGELOG.md) +- [google-cloud-billing-budgets==1.14.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-billing-budgets/CHANGELOG.md) +- [google-cloud-billing==1.13.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-billing/CHANGELOG.md) +- [google-cloud-binary-authorization==1.10.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-binary-authorization/CHANGELOG.md) +- [google-cloud-build==3.23.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-build/CHANGELOG.md) +- [google-cloud-certificate-manager==1.6.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-certificate-manager/CHANGELOG.md) +- [google-cloud-channel==1.18.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-channel/CHANGELOG.md) +- [google-cloud-cloudquotas==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-cloudquotas/CHANGELOG.md) +- [google-cloud-commerce-consumer-procurement==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-commerce-consumer-procurement/CHANGELOG.md) +- [google-cloud-common==1.3.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-common/CHANGELOG.md) +- [google-cloud-compute==1.17.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-compute/CHANGELOG.md) +- [google-cloud-confidentialcomputing==0.4.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-confidentialcomputing/CHANGELOG.md) +- [google-cloud-config==0.1.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-config/CHANGELOG.md) +- [google-cloud-contact-center-insights==1.17.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-contact-center-insights/CHANGELOG.md) +- [google-cloud-container==2.42.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-container/CHANGELOG.md) +- [google-cloud-containeranalysis==2.14.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-containeranalysis/CHANGELOG.md) +- [google-cloud-contentwarehouse==0.7.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-contentwarehouse/CHANGELOG.md) +- [google-cloud-data-fusion==1.10.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-data-fusion/CHANGELOG.md) +- [google-cloud-data-qna==0.10.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-data-qna/CHANGELOG.md) +- [google-cloud-datacatalog-lineage==0.3.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datacatalog-lineage/CHANGELOG.md) +- [google-cloud-datacatalog==3.18.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datacatalog/CHANGELOG.md) +- [google-cloud-dataflow-client==0.8.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataflow-client/CHANGELOG.md) +- [google-cloud-dataform==0.5.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataform/CHANGELOG.md) +- [google-cloud-datalabeling==1.10.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datalabeling/CHANGELOG.md) +- [google-cloud-dataplex==1.12.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataplex/CHANGELOG.md) +- [google-cloud-dataproc-metastore==1.15.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataproc-metastore/CHANGELOG.md) +- [google-cloud-dataproc==5.9.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataproc/CHANGELOG.md) +- [google-cloud-datastream==1.9.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datastream/CHANGELOG.md) +- [google-cloud-deploy==1.17.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-deploy/CHANGELOG.md) +- [google-cloud-dialogflow-cx==1.32.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dialogflow-cx/CHANGELOG.md) +- [google-cloud-dialogflow==2.28.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dialogflow/CHANGELOG.md) +- [google-cloud-discoveryengine==0.11.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-discoveryengine/CHANGELOG.md) +- [google-cloud-dlp==3.15.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dlp/CHANGELOG.md) +- [google-cloud-dms==1.9.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dms/CHANGELOG.md) +- [google-cloud-documentai==2.24.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-documentai/CHANGELOG.md) +- [google-cloud-domains==1.7.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-domains/CHANGELOG.md) +- [google-cloud-edgecontainer==0.5.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-edgecontainer/CHANGELOG.md) +- [google-cloud-edgenetwork==0.1.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-edgenetwork/CHANGELOG.md) +- [google-cloud-enterpriseknowledgegraph==0.3.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-enterpriseknowledgegraph/CHANGELOG.md) +- [google-cloud-essential-contacts==1.7.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-essential-contacts/CHANGELOG.md) +- [google-cloud-eventarc-publishing==0.6.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-eventarc-publishing/CHANGELOG.md) +- [google-cloud-eventarc==1.11.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-eventarc/CHANGELOG.md) +- [google-cloud-filestore==1.9.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-filestore/CHANGELOG.md) +- [google-cloud-functions==1.16.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-functions/CHANGELOG.md) +- [google-cloud-gke-backup==0.5.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-backup/CHANGELOG.md) +- [google-cloud-gke-connect-gateway==0.8.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-connect-gateway/CHANGELOG.md) +- [google-cloud-gke-hub==1.13.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-hub/CHANGELOG.md) +- [google-cloud-gke-multicloud==0.6.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-multicloud/CHANGELOG.md) +- [google-cloud-gsuiteaddons==0.3.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gsuiteaddons/CHANGELOG.md) +- [google-cloud-iam-logging==1.3.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iam-logging/CHANGELOG.md) +- [google-cloud-iam==2.14.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iam/CHANGELOG.md) +- [google-cloud-iap==1.13.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iap/CHANGELOG.md) +- [google-cloud-ids==1.7.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-ids/CHANGELOG.md) +- [google-cloud-kms-inventory==0.2.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-kms-inventory/CHANGELOG.md) +- [google-cloud-kms==2.21.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-kms/CHANGELOG.md) +- [google-cloud-language==2.13.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-language/CHANGELOG.md) +- [google-cloud-life-sciences==0.9.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-life-sciences/CHANGELOG.md) +- [google-cloud-managed-identities==1.9.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-managed-identities/CHANGELOG.md) +- [google-cloud-media-translation==0.11.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-media-translation/CHANGELOG.md) +- [google-cloud-memcache==1.9.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-memcache/CHANGELOG.md) +- [google-cloud-migrationcenter==0.1.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-migrationcenter/CHANGELOG.md) +- [google-cloud-monitoring-dashboards==2.15.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring-dashboards/CHANGELOG.md) +- [google-cloud-monitoring-metrics-scopes==1.6.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring-metrics-scopes/CHANGELOG.md) +- [google-cloud-monitoring==2.19.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring/CHANGELOG.md) +- [google-cloud-netapp==0.3.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-netapp/CHANGELOG.md) +- [google-cloud-network-connectivity==2.4.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-connectivity/CHANGELOG.md) +- [google-cloud-network-management==1.13.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-management/CHANGELOG.md) +- [google-cloud-network-security==0.9.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-security/CHANGELOG.md) +- [google-cloud-network-services==0.5.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-services/CHANGELOG.md) +- [google-cloud-notebooks==1.10.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-notebooks/CHANGELOG.md) +- [google-cloud-optimization==1.8.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-optimization/CHANGELOG.md) +- [google-cloud-orchestration-airflow==1.12.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-orchestration-airflow/CHANGELOG.md) +- [google-cloud-os-config==1.17.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-os-config/CHANGELOG.md) +- [google-cloud-os-login==2.14.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-os-login/CHANGELOG.md) +- [google-cloud-parallelstore==0.1.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-parallelstore/CHANGELOG.md) +- [google-cloud-phishing-protection==1.11.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-phishing-protection/CHANGELOG.md) +- [google-cloud-policy-troubleshooter==1.11.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policy-troubleshooter/CHANGELOG.md) +- [google-cloud-policysimulator==0.1.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policysimulator/CHANGELOG.md) +- [google-cloud-policytroubleshooter-iam==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policytroubleshooter-iam/CHANGELOG.md) +- [google-cloud-private-ca==1.10.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-private-ca/CHANGELOG.md) +- [google-cloud-private-catalog==0.9.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-private-catalog/CHANGELOG.md) +- [google-cloud-public-ca==0.3.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-public-ca/CHANGELOG.md) +- [google-cloud-rapidmigrationassessment==0.1.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-rapidmigrationassessment/CHANGELOG.md) +- [google-cloud-recaptcha-enterprise==1.18.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recaptcha-enterprise/CHANGELOG.md) +- [google-cloud-recommendations-ai==0.10.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recommendations-ai/CHANGELOG.md) +- [google-cloud-recommender==2.15.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recommender/CHANGELOG.md) +- [google-cloud-redis-cluster==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-redis-cluster/CHANGELOG.md) +- [google-cloud-redis==2.15.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-redis/CHANGELOG.md) +- [google-cloud-resource-manager==1.12.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-resource-manager/CHANGELOG.md) +- [google-cloud-resource-settings==1.9.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-resource-settings/CHANGELOG.md) +- [google-cloud-retail==1.20.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-retail/CHANGELOG.md) +- [google-cloud-run==0.10.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-run/CHANGELOG.md) +- [google-cloud-scheduler==2.13.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-scheduler/CHANGELOG.md) +- [google-cloud-secret-manager==2.18.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-secret-manager/CHANGELOG.md) +- [google-cloud-securesourcemanager==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securesourcemanager/CHANGELOG.md) +- [google-cloud-securitycenter==1.28.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter/CHANGELOG.md) +- [google-cloud-securitycentermanagement==0.1.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycentermanagement/CHANGELOG.md) +- [google-cloud-service-control==1.12.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-control/CHANGELOG.md) +- [google-cloud-service-directory==1.11.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-directory/CHANGELOG.md) +- [google-cloud-service-management==1.8.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-management/CHANGELOG.md) +- [google-cloud-service-usage==1.10.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-usage/CHANGELOG.md) +- [google-cloud-servicehealth==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-servicehealth/CHANGELOG.md) +- [google-cloud-shell==1.9.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-shell/CHANGELOG.md) +- [google-cloud-source-context==1.5.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-source-context/CHANGELOG.md) +- [google-cloud-speech==2.25.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-speech/CHANGELOG.md) +- [google-cloud-storage-transfer==1.11.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storage-transfer/CHANGELOG.md) +- [google-cloud-storageinsights==0.1.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storageinsights/CHANGELOG.md) +- [google-cloud-support==0.1.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-support/CHANGELOG.md) +- [google-cloud-talent==2.13.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-talent/CHANGELOG.md) +- [google-cloud-tasks==2.16.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-tasks/CHANGELOG.md) +- [google-cloud-telcoautomation==0.2.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-telcoautomation/CHANGELOG.md) +- [google-cloud-texttospeech==2.16.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-texttospeech/CHANGELOG.md) +- [google-cloud-tpu==1.18.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-tpu/CHANGELOG.md) +- [google-cloud-trace==1.13.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-trace/CHANGELOG.md) +- [google-cloud-translate==3.15.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-translate/CHANGELOG.md) +- [google-cloud-video-live-stream==1.7.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-live-stream/CHANGELOG.md) +- [google-cloud-video-stitcher==0.7.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-stitcher/CHANGELOG.md) +- [google-cloud-video-transcoder==1.12.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-transcoder/CHANGELOG.md) +- [google-cloud-videointelligence==2.13.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-videointelligence/CHANGELOG.md) +- [google-cloud-vision==3.7.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vision/CHANGELOG.md) +- [google-cloud-vm-migration==1.8.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vm-migration/CHANGELOG.md) +- [google-cloud-vmwareengine==1.4.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vmwareengine/CHANGELOG.md) +- [google-cloud-vpc-access==1.10.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vpc-access/CHANGELOG.md) +- [google-cloud-webrisk==1.14.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-webrisk/CHANGELOG.md) +- [google-cloud-websecurityscanner==1.14.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-websecurityscanner/CHANGELOG.md) +- [google-cloud-workflows==1.14.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workflows/CHANGELOG.md) +- [google-cloud-workstations==0.5.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workstations/CHANGELOG.md) +- [google-geo-type==0.3.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-geo-type/CHANGELOG.md) +- [google-maps-addressvalidation==0.3.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-addressvalidation/CHANGELOG.md) +- [google-maps-fleetengine-delivery==0.1.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-fleetengine-delivery/CHANGELOG.md) +- [google-maps-fleetengine==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-fleetengine/CHANGELOG.md) +- [google-maps-mapsplatformdatasets==0.3.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-mapsplatformdatasets/CHANGELOG.md) +- [google-maps-places==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-places/CHANGELOG.md) +- [google-maps-routing==0.6.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-routing/CHANGELOG.md) +- [google-shopping-css==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-css/CHANGELOG.md) +- [google-shopping-merchant-inventories==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-inventories/CHANGELOG.md) +- [google-shopping-merchant-reports==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-reports/CHANGELOG.md) +- [google-shopping-type==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-type/CHANGELOG.md) +- [grafeas==1.9.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/grafeas/CHANGELOG.md) diff --git a/packages/google-ai-generativelanguage/CHANGELOG.md b/packages/google-ai-generativelanguage/CHANGELOG.md index 6a63142c2992..11721ab7e64c 100644 --- a/packages/google-ai-generativelanguage/CHANGELOG.md +++ b/packages/google-ai-generativelanguage/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.5.4](https://github.com/googleapis/google-cloud-python/compare/google-ai-generativelanguage-v0.5.3...google-ai-generativelanguage-v0.5.4) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [0.5.3](https://github.com/googleapis/google-cloud-python/compare/google-ai-generativelanguage-v0.5.2...google-ai-generativelanguage-v0.5.3) (2024-02-22) 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 7951a72dc56f..06d63171de69 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.5.3" # {x-release-please-version} +__version__ = "0.5.4" # {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 7951a72dc56f..06d63171de69 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.5.3" # {x-release-please-version} +__version__ = "0.5.4" # {x-release-please-version} 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 7951a72dc56f..06d63171de69 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.5.3" # {x-release-please-version} +__version__ = "0.5.4" # {x-release-please-version} 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 7951a72dc56f..06d63171de69 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.5.3" # {x-release-please-version} +__version__ = "0.5.4" # {x-release-please-version} 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 7951a72dc56f..06d63171de69 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.5.3" # {x-release-please-version} +__version__ = "0.5.4" # {x-release-please-version} 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 b7a7fa411ac5..7f618b1c9adc 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.5.3" + "version": "0.5.4" }, "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 a28fd2d546d1..8950ce5fdc20 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.5.3" + "version": "0.5.4" }, "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 0cd9dfb45a51..c784607a3924 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.5.3" + "version": "0.5.4" }, "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 606595e6771b..32589b117b30 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.5.3" + "version": "0.5.4" }, "snippets": [ { diff --git a/packages/google-ai-generativelanguage/setup.py b/packages/google-ai-generativelanguage/setup.py index 32a6301cde1a..17708ef4bfb5 100644 --- a/packages/google-ai-generativelanguage/setup.py +++ b/packages/google-ai-generativelanguage/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-analytics-admin/CHANGELOG.md b/packages/google-analytics-admin/CHANGELOG.md index ad43c9aa1fc7..1f2b2ca132e9 100644 --- a/packages/google-analytics-admin/CHANGELOG.md +++ b/packages/google-analytics-admin/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.22.7](https://github.com/googleapis/google-cloud-python/compare/google-analytics-admin-v0.22.6...google-analytics-admin-v0.22.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [0.22.6](https://github.com/googleapis/google-cloud-python/compare/google-analytics-admin-v0.22.5...google-analytics-admin-v0.22.6) (2024-02-22) 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 3684f82fd0c1..56cd6227923b 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.22.6" # {x-release-please-version} +__version__ = "0.22.7" # {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 3684f82fd0c1..56cd6227923b 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.22.6" # {x-release-please-version} +__version__ = "0.22.7" # {x-release-please-version} 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 3684f82fd0c1..56cd6227923b 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.22.6" # {x-release-please-version} +__version__ = "0.22.7" # {x-release-please-version} 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 50b98e87bd45..d3af72a94341 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.22.6" + "version": "0.22.7" }, "snippets": [ { diff --git a/packages/google-analytics-admin/setup.py b/packages/google-analytics-admin/setup.py index dac0742f9163..f5042a93654f 100644 --- a/packages/google-analytics-admin/setup.py +++ b/packages/google-analytics-admin/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-analytics-data/CHANGELOG.md b/packages/google-analytics-data/CHANGELOG.md index d9165e8948f7..d94861f0a6bc 100644 --- a/packages/google-analytics-data/CHANGELOG.md +++ b/packages/google-analytics-data/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.18.7](https://github.com/googleapis/google-cloud-python/compare/google-analytics-data-v0.18.6...google-analytics-data-v0.18.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [0.18.6](https://github.com/googleapis/google-cloud-python/compare/google-analytics-data-v0.18.5...google-analytics-data-v0.18.6) (2024-02-22) 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 29a944f6a360..4d434dc7b617 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.6" # {x-release-please-version} +__version__ = "0.18.7" # {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 29a944f6a360..4d434dc7b617 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.6" # {x-release-please-version} +__version__ = "0.18.7" # {x-release-please-version} 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 29a944f6a360..4d434dc7b617 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.6" # {x-release-please-version} +__version__ = "0.18.7" # {x-release-please-version} 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 2b07fd81c1a6..9d27055fe7bf 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.6" + "version": "0.18.7" }, "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 a7f235e60dfb..6195177ec5f4 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.6" + "version": "0.18.7" }, "snippets": [ { diff --git a/packages/google-analytics-data/setup.py b/packages/google-analytics-data/setup.py index ead41840c8e3..8afdfcc5f509 100644 --- a/packages/google-analytics-data/setup.py +++ b/packages/google-analytics-data/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-apps-card/.OwlBot.yaml b/packages/google-apps-card/.OwlBot.yaml new file mode 100644 index 000000000000..5d11a56a79d7 --- /dev/null +++ b/packages/google-apps-card/.OwlBot.yaml @@ -0,0 +1,18 @@ +# Copyright 2022 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. + +deep-copy-regex: + - source: /google/apps/card/(v.*)/.*-py + dest: /owl-bot-staging/google-apps-card/$1 +api-name: google-apps-card diff --git a/packages/google-apps-card/.coveragerc b/packages/google-apps-card/.coveragerc new file mode 100644 index 000000000000..4d0a316cdc27 --- /dev/null +++ b/packages/google-apps-card/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/apps/card/__init__.py + google/apps/card/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/packages/google-apps-card/.flake8 b/packages/google-apps-card/.flake8 new file mode 100644 index 000000000000..87f6e408c47d --- /dev/null +++ b/packages/google-apps-card/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2023 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 +# +# https://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 by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E231, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/packages/google-apps-card/.gitignore b/packages/google-apps-card/.gitignore new file mode 100644 index 000000000000..b4243ced74e4 --- /dev/null +++ b/packages/google-apps-card/.gitignore @@ -0,0 +1,63 @@ +*.py[cod] +*.sw[op] + +# C extensions +*.so + +# Packages +*.egg +*.egg-info +dist +build +eggs +.eggs +parts +bin +var +sdist +develop-eggs +.installed.cfg +lib +lib64 +__pycache__ + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.nox +.cache +.pytest_cache + + +# Mac +.DS_Store + +# JetBrains +.idea + +# VS Code +.vscode + +# emacs +*~ + +# Built documentation +docs/_build +bigquery/docs/generated +docs.metadata + +# Virtual environment +env/ + +# Test logs +coverage.xml +*sponge_log.xml + +# System test environment variables. +system_tests/local_test_setup + +# Make sure a generated file isn't accidentally committed. +pylintrc +pylintrc.test diff --git a/packages/google-apps-card/.repo-metadata.json b/packages/google-apps-card/.repo-metadata.json new file mode 100644 index 000000000000..52344458c237 --- /dev/null +++ b/packages/google-apps-card/.repo-metadata.json @@ -0,0 +1,17 @@ +{ + "name": "google-apps-card", + "name_pretty": "Google Apps Card Protos", + "api_description": "Google Apps Card Protos", + "product_documentation": "https://developers.google.com/chat", + "client_documentation": "https://googleapis.dev/python/google-apps-card/latest", + "issue_tracker": "https://github.com/googleapis/google-cloud-python/issues", + "release_level": "preview", + "language": "python", + "library_type": "GAPIC_AUTO", + "repo": "googleapis/google-cloud-python", + "distribution_name": "google-apps-card", + "api_id": "card.googleapis.com", + "default_version": "v1", + "codeowner_team": "", + "api_shortname": "card" +} diff --git a/packages/google-apps-card/CHANGELOG.md b/packages/google-apps-card/CHANGELOG.md new file mode 100644 index 000000000000..4a3b37de2d6d --- /dev/null +++ b/packages/google-apps-card/CHANGELOG.md @@ -0,0 +1,17 @@ +# Changelog + +## [0.1.1](https://github.com/googleapis/google-cloud-python/compare/google-apps-card-v0.1.0...google-apps-card-v0.1.1) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + +## 0.1.0 (2024-03-04) + + +### Features + +* add initial files for google.apps.card.v1 ([#12370](https://github.com/googleapis/google-cloud-python/issues/12370)) ([394a05f](https://github.com/googleapis/google-cloud-python/commit/394a05fe2b3d2582c4f161efc574fe8e1625c913)) + +## Changelog diff --git a/packages/google-apps-card/CODE_OF_CONDUCT.md b/packages/google-apps-card/CODE_OF_CONDUCT.md new file mode 100644 index 000000000000..039f43681204 --- /dev/null +++ b/packages/google-apps-card/CODE_OF_CONDUCT.md @@ -0,0 +1,95 @@ + +# Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of +experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, or to ban temporarily or permanently any +contributor for other behaviors that they deem inappropriate, threatening, +offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +This Code of Conduct also applies outside the project spaces when the Project +Steward has a reasonable belief that an individual's behavior may have a +negative impact on the project or its community. + +## Conflict Resolution + +We do not believe that all conflict is bad; healthy debate and disagreement +often yield positive results. However, it is never okay to be disrespectful or +to engage in behavior that violates the project’s code of conduct. + +If you see someone violating the code of conduct, you are encouraged to address +the behavior directly with those involved. Many issues can be resolved quickly +and easily, and this gives people more control over the outcome of their +dispute. If you are unable to resolve the matter for any reason, or if the +behavior is threatening or harassing, report it. We are dedicated to providing +an environment where participants feel welcome and safe. + + +Reports should be directed to *googleapis-stewards@google.com*, the +Project Steward(s) for *Google Cloud Client Libraries*. It is the Project Steward’s duty to +receive and address reported violations of the code of conduct. They will then +work with a committee consisting of representatives from the Open Source +Programs Office and the Google Open Source Strategy team. If for any reason you +are uncomfortable reaching out to the Project Steward, please email +opensource@google.com. + +We will investigate every complaint, but you may not receive a direct response. +We will use our discretion in determining when and how to follow up on reported +incidents, which may range from not taking action to permanent expulsion from +the project and project-sponsored spaces. We will notify the accused of the +report and provide them an opportunity to discuss it before any action is taken. +The identity of the reporter will be omitted from the details of the report +supplied to the accused. In potentially harmful situations, such as ongoing +harassment or threats to anyone's safety, we may take action without notice. + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 1.4, +available at +https://www.contributor-covenant.org/version/1/4/code-of-conduct.html \ No newline at end of file diff --git a/packages/google-apps-card/CONTRIBUTING.rst b/packages/google-apps-card/CONTRIBUTING.rst new file mode 100644 index 000000000000..f21262ffe7ad --- /dev/null +++ b/packages/google-apps-card/CONTRIBUTING.rst @@ -0,0 +1,271 @@ +.. Generated by synthtool. DO NOT EDIT! +############ +Contributing +############ + +#. **Please sign one of the contributor license agreements below.** +#. Fork the repo, develop and test your code changes, add docs. +#. Make sure that your commit messages clearly describe the changes. +#. Send a pull request. (Please Read: `Faster Pull Request Reviews`_) + +.. _Faster Pull Request Reviews: https://github.com/kubernetes/community/blob/master/contributors/guide/pull-requests.md#best-practices-for-faster-reviews + +.. contents:: Here are some guidelines for hacking on the Google Cloud Client libraries. + +*************** +Adding Features +*************** + +In order to add a feature: + +- The feature must be documented in both the API and narrative + documentation. + +- The feature must work fully on the following CPython versions: + 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + +- The feature must not add unnecessary dependencies (where + "unnecessary" is of course subjective, but new dependencies should + be discussed). + +**************************** +Using a Development Checkout +**************************** + +You'll have to create a development environment using a Git checkout: + +- While logged into your GitHub account, navigate to the + ``google-cloud-python`` `repo`_ on GitHub. + +- Fork and clone the ``google-cloud-python`` repository to your GitHub account by + clicking the "Fork" button. + +- Clone your fork of ``google-cloud-python`` from your GitHub account to your local + computer, substituting your account username and specifying the destination + as ``hack-on-google-cloud-python``. E.g.:: + + $ cd ${HOME} + $ git clone git@github.com:USERNAME/google-cloud-python.git hack-on-google-cloud-python + $ cd hack-on-google-cloud-python + # Configure remotes such that you can pull changes from the googleapis/google-cloud-python + # repository into your local repository. + $ git remote add upstream git@github.com:googleapis/google-cloud-python.git + # fetch and merge changes from upstream into main + $ git fetch upstream + $ git merge upstream/main + +Now your local repo is set up such that you will push changes to your GitHub +repo, from which you can submit a pull request. + +To work on the codebase and run the tests, we recommend using ``nox``, +but you can also use a ``virtualenv`` of your own creation. + +.. _repo: https://github.com/googleapis/google-cloud-python + +Using ``nox`` +============= + +We use `nox `__ to instrument our tests. + +- To test your changes, run unit tests with ``nox``:: + $ nox -s unit + +- To run a single unit test:: + + $ nox -s unit-3.12 -- -k + + + .. note:: + + The unit tests and system tests are described in the + ``noxfile.py`` files in each directory. + +.. nox: https://pypi.org/project/nox/ + +***************************************** +I'm getting weird errors... Can you help? +***************************************** + +If the error mentions ``Python.h`` not being found, +install ``python-dev`` and try again. +On Debian/Ubuntu:: + + $ sudo apt-get install python-dev + +************ +Coding Style +************ +- We use the automatic code formatter ``black``. You can run it using + the nox session ``blacken``. This will eliminate many lint errors. Run via:: + + $ nox -s blacken + +- PEP8 compliance is required, with exceptions defined in the linter configuration. + If you have ``nox`` installed, you can test that you have not introduced + any non-compliant code via:: + + $ nox -s lint + +- In order to make ``nox -s lint`` run faster, you can set some environment + variables:: + + export GOOGLE_CLOUD_TESTING_REMOTE="upstream" + export GOOGLE_CLOUD_TESTING_BRANCH="main" + + By doing this, you are specifying the location of the most up-to-date + version of ``google-cloud-python``. The + remote name ``upstream`` should point to the official ``googleapis`` + checkout and the branch should be the default branch on that remote (``main``). + +- This repository contains configuration for the + `pre-commit `__ tool, which automates checking + our linters during a commit. If you have it installed on your ``$PATH``, + you can enable enforcing those checks via: + +.. code-block:: bash + + $ pre-commit install + pre-commit installed at .git/hooks/pre-commit + +Exceptions to PEP8: + +- Many unit tests use a helper method, ``_call_fut`` ("FUT" is short for + "Function-Under-Test"), which is PEP8-incompliant, but more readable. + Some also use a local variable, ``MUT`` (short for "Module-Under-Test"). + +******************** +Running System Tests +******************** + +- To run system tests, you can execute:: + + # Run all system tests + $ nox -s system + + # Run a single system test + $ nox -s system-3.12 -- -k + + + .. note:: + + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + For expediency, we do not run them in older versions of Python 3. + + This alone will not run the tests. You'll need to change some local + auth settings and change some configuration in your project to + run all the tests. + +- System tests will be run against an actual project. You should use local credentials from gcloud when possible. See `Best practices for application authentication `__. Some tests require a service account. For those tests see `Authenticating as a service account `__. + +************* +Test Coverage +************* + +- The codebase *must* have 100% test statement coverage after each commit. + You can test coverage via ``nox -s cover``. + +****************************************************** +Documentation Coverage and Building HTML Documentation +****************************************************** + +If you fix a bug, and the bug requires an API or behavior modification, all +documentation in this package which references that API or behavior must be +changed to reflect the bug fix, ideally in the same commit that fixes the bug +or adds the feature. + +Build the docs via: + + $ nox -s docs + +************************* +Samples and code snippets +************************* + +Code samples and snippets live in the `samples/` catalogue. Feel free to +provide more examples, but make sure to write tests for those examples. +Each folder containing example code requires its own `noxfile.py` script +which automates testing. If you decide to create a new folder, you can +base it on the `samples/snippets` folder (providing `noxfile.py` and +the requirements files). + +The tests will run against a real Google Cloud Project, so you should +configure them just like the System Tests. + +- To run sample tests, you can execute:: + + # Run all tests in a folder + $ cd samples/snippets + $ nox -s py-3.8 + + # Run a single sample test + $ cd samples/snippets + $ nox -s py-3.8 -- -k + +******************************************** +Note About ``README`` as it pertains to PyPI +******************************************** + +The `description on PyPI`_ for the project comes directly from the +``README``. Due to the reStructuredText (``rst``) parser used by +PyPI, relative links which will work on GitHub (e.g. ``CONTRIBUTING.rst`` +instead of +``https://github.com/googleapis/google-cloud-python/blob/main/CONTRIBUTING.rst``) +may cause problems creating links or rendering the description. + +.. _description on PyPI: https://pypi.org/project/google-apps-card + + +************************* +Supported Python Versions +************************* + +We support: + +- `Python 3.7`_ +- `Python 3.8`_ +- `Python 3.9`_ +- `Python 3.10`_ +- `Python 3.11`_ +- `Python 3.12`_ + +.. _Python 3.7: https://docs.python.org/3.7/ +.. _Python 3.8: https://docs.python.org/3.8/ +.. _Python 3.9: https://docs.python.org/3.9/ +.. _Python 3.10: https://docs.python.org/3.10/ +.. _Python 3.11: https://docs.python.org/3.11/ +.. _Python 3.12: https://docs.python.org/3.12/ + + +Supported versions can be found in our ``noxfile.py`` `config`_. + +.. _config: https://github.com/googleapis/google-cloud-python/blob/main/packages/google-apps-card/noxfile.py + + +********** +Versioning +********** + +This library follows `Semantic Versioning`_. + +.. _Semantic Versioning: http://semver.org/ + +Some packages are currently in major version zero (``0.y.z``), which means that +anything may change at any time and the public API should not be considered +stable. + +****************************** +Contributor License Agreements +****************************** + +Before we can accept your pull requests you'll need to sign a Contributor +License Agreement (CLA): + +- **If you are an individual writing original source code** and **you own the + intellectual property**, then you'll need to sign an + `individual CLA `__. +- **If you work for a company that wants to allow you to contribute your work**, + then you'll need to sign a + `corporate CLA `__. + +You can sign these electronically (just scroll to the bottom). After that, +we'll be able to accept your pull requests. diff --git a/packages/google-apps-card/LICENSE b/packages/google-apps-card/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/packages/google-apps-card/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/packages/google-apps-card/MANIFEST.in b/packages/google-apps-card/MANIFEST.in new file mode 100644 index 000000000000..e0a66705318e --- /dev/null +++ b/packages/google-apps-card/MANIFEST.in @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2023 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 +# +# https://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 by synthtool. DO NOT EDIT! +include README.rst LICENSE +recursive-include google *.json *.proto py.typed +recursive-include tests * +global-exclude *.py[co] +global-exclude __pycache__ + +# Exclude scripts for samples readmegen +prune scripts/readme-gen diff --git a/packages/google-apps-card/README.rst b/packages/google-apps-card/README.rst new file mode 100644 index 000000000000..0d97915d9035 --- /dev/null +++ b/packages/google-apps-card/README.rst @@ -0,0 +1,108 @@ +Python Client for Google Apps Card Protos +========================================= + +|preview| |pypi| |versions| + +`Google Apps Card Protos`_: Google Apps Card Protos + +- `Client Library Documentation`_ +- `Product Documentation`_ + +.. |preview| image:: https://img.shields.io/badge/support-preview-orange.svg + :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#stability-levels +.. |pypi| image:: https://img.shields.io/pypi/v/google-apps-card.svg + :target: https://pypi.org/project/google-apps-card/ +.. |versions| image:: https://img.shields.io/pypi/pyversions/google-apps-card.svg + :target: https://pypi.org/project/google-apps-card/ +.. _Google Apps Card Protos: https://developers.google.com/chat +.. _Client Library Documentation: https://googleapis.dev/python/google-apps-card/latest +.. _Product Documentation: https://developers.google.com/chat + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. `Enable the Google Apps Card Protos.`_ +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Enable the Google Apps Card Protos.: https://developers.google.com/chat +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a virtual environment using `venv`_. `venv`_ is a tool that +creates isolated Python environments. These isolated environments can have separate +versions of Python packages, which allows you to isolate one project's dependencies +from the dependencies of other projects. + +With `venv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`venv`: https://docs.python.org/3/library/venv.html + + +Code samples and snippets +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Code samples and snippets live in the `samples/`_ folder. + +.. _samples/: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-card/samples + + +Supported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^ +Our client libraries are compatible with all current `active`_ and `maintenance`_ versions of +Python. + +Python >= 3.7 + +.. _active: https://devguide.python.org/devcycle/#in-development-main-branch +.. _maintenance: https://devguide.python.org/devcycle/#maintenance-branches + +Unsupported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Python <= 3.6 + +If you are using an `end-of-life`_ +version of Python, we recommend that you update as soon as possible to an actively supported version. + +.. _end-of-life: https://devguide.python.org/devcycle/#end-of-life-branches + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + pip install google-apps-card + + +Windows +^^^^^^^ + +.. code-block:: console + + py -m venv + .\\Scripts\activate + pip install google-apps-card + +Next Steps +~~~~~~~~~~ + +- Read the `Client Library Documentation`_ for Google Apps Card Protos + to see other available methods on the client. +- Read the `Google Apps Card Protos Product documentation`_ to learn + more about the product and see How-to Guides. +- View this `README`_ to see the full list of Cloud + APIs that we cover. + +.. _Google Apps Card Protos Product documentation: https://developers.google.com/chat +.. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst diff --git a/packages/google-apps-card/docs/CHANGELOG.md b/packages/google-apps-card/docs/CHANGELOG.md new file mode 120000 index 000000000000..04c99a55caae --- /dev/null +++ b/packages/google-apps-card/docs/CHANGELOG.md @@ -0,0 +1 @@ +../CHANGELOG.md \ No newline at end of file diff --git a/packages/google-apps-card/docs/README.rst b/packages/google-apps-card/docs/README.rst new file mode 120000 index 000000000000..89a0106941ff --- /dev/null +++ b/packages/google-apps-card/docs/README.rst @@ -0,0 +1 @@ +../README.rst \ No newline at end of file diff --git a/packages/google-apps-card/docs/_static/custom.css b/packages/google-apps-card/docs/_static/custom.css new file mode 100644 index 000000000000..b0a295464b23 --- /dev/null +++ b/packages/google-apps-card/docs/_static/custom.css @@ -0,0 +1,20 @@ +div#python2-eol { + border-color: red; + border-width: medium; +} + +/* Ensure minimum width for 'Parameters' / 'Returns' column */ +dl.field-list > dt { + min-width: 100px +} + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/packages/google-apps-card/docs/_templates/layout.html b/packages/google-apps-card/docs/_templates/layout.html new file mode 100644 index 000000000000..6316a537f72b --- /dev/null +++ b/packages/google-apps-card/docs/_templates/layout.html @@ -0,0 +1,50 @@ + +{% extends "!layout.html" %} +{%- block content %} +{%- if theme_fixed_sidebar|lower == 'true' %} +
+ {{ sidebar() }} + {%- block document %} +
+ {%- if render_sidebar %} +
+ {%- endif %} + + {%- block relbar_top %} + {%- if theme_show_relbar_top|tobool %} + + {%- endif %} + {% endblock %} + +
+
+ As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please + visit Python 2 support on Google Cloud. +
+ {% block body %} {% endblock %} +
+ + {%- block relbar_bottom %} + {%- if theme_show_relbar_bottom|tobool %} + + {%- endif %} + {% endblock %} + + {%- if render_sidebar %} +
+ {%- endif %} +
+ {%- endblock %} +
+
+{%- else %} +{{ super() }} +{%- endif %} +{%- endblock %} diff --git a/packages/google-apps-card/docs/card_v1/services_.rst b/packages/google-apps-card/docs/card_v1/services_.rst new file mode 100644 index 000000000000..582c850104f3 --- /dev/null +++ b/packages/google-apps-card/docs/card_v1/services_.rst @@ -0,0 +1,4 @@ +Services for Google Apps Card v1 API +==================================== +.. toctree:: + :maxdepth: 2 diff --git a/packages/google-apps-card/docs/card_v1/types_.rst b/packages/google-apps-card/docs/card_v1/types_.rst new file mode 100644 index 000000000000..ed5e6dc5e6d0 --- /dev/null +++ b/packages/google-apps-card/docs/card_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Apps Card v1 API +================================= + +.. automodule:: google.apps.card_v1.types + :members: + :show-inheritance: diff --git a/packages/google-apps-card/docs/conf.py b/packages/google-apps-card/docs/conf.py new file mode 100644 index 000000000000..bb4463d27528 --- /dev/null +++ b/packages/google-apps-card/docs/conf.py @@ -0,0 +1,384 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# +# google-apps-card documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import os +import shlex +import sys + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + +__version__ = "" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.5.5" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.doctest", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", + "recommonmark", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_options = {"members": True} +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = "google-apps-card" +copyright = "2019, Google" +author = "Google APIs" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [ + "_build", + "**/.nox/**/*", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for google-apps-card", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-apps-card-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + #'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + #'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + #'preamble': '', + # Latex figure (float) alignment + #'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-apps-card.tex", + "google-apps-card Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-apps-card", + "google-apps-card Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-apps-card", + "google-apps-card Documentation", + author, + "google-apps-card", + "google-apps-card Library", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), + "google.api_core": ( + "https://googleapis.dev/python/google-api-core/latest/", + None, + ), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/packages/google-apps-card/docs/index.rst b/packages/google-apps-card/docs/index.rst new file mode 100644 index 000000000000..0eccdef92528 --- /dev/null +++ b/packages/google-apps-card/docs/index.rst @@ -0,0 +1,23 @@ +.. include:: README.rst + +.. include:: multiprocessing.rst + + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + card_v1/services_ + card_v1/types_ + + +Changelog +--------- + +For a list of all ``google-apps-card`` releases: + +.. toctree:: + :maxdepth: 2 + + CHANGELOG diff --git a/packages/google-apps-card/docs/multiprocessing.rst b/packages/google-apps-card/docs/multiprocessing.rst new file mode 100644 index 000000000000..536d17b2ea65 --- /dev/null +++ b/packages/google-apps-card/docs/multiprocessing.rst @@ -0,0 +1,7 @@ +.. note:: + + Because this client uses :mod:`grpc` library, it is safe to + share instances across threads. In multiprocessing scenarios, the best + practice is to create client instances *after* the invocation of + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or + :class:`multiprocessing.Process`. diff --git a/packages/google-apps-card/google/apps/card/__init__.py b/packages/google-apps-card/google/apps/card/__init__.py new file mode 100644 index 000000000000..5e3135c90efe --- /dev/null +++ b/packages/google-apps-card/google/apps/card/__init__.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 google.apps.card import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.apps.card_v1.types.card import ( + Action, + BorderStyle, + Button, + ButtonList, + Card, + Columns, + DateTimePicker, + DecoratedText, + Divider, + Grid, + Icon, + Image, + ImageComponent, + ImageCropStyle, + OnClick, + OpenLink, + SelectionInput, + Suggestions, + TextInput, + TextParagraph, + Widget, +) + +__all__ = ( + "Action", + "BorderStyle", + "Button", + "ButtonList", + "Card", + "Columns", + "DateTimePicker", + "DecoratedText", + "Divider", + "Grid", + "Icon", + "Image", + "ImageComponent", + "ImageCropStyle", + "OnClick", + "OpenLink", + "SelectionInput", + "Suggestions", + "TextInput", + "TextParagraph", + "Widget", +) diff --git a/packages/google-apps-card/google/apps/card/gapic_version.py b/packages/google-apps-card/google/apps/card/gapic_version.py new file mode 100644 index 000000000000..123d60293175 --- /dev/null +++ b/packages/google-apps-card/google/apps/card/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# +__version__ = "0.1.1" # {x-release-please-version} diff --git a/packages/google-apps-card/google/apps/card/py.typed b/packages/google-apps-card/google/apps/card/py.typed new file mode 100644 index 000000000000..99846f9bd47e --- /dev/null +++ b/packages/google-apps-card/google/apps/card/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-apps-card package uses inline types. diff --git a/packages/google-apps-card/google/apps/card_v1/__init__.py b/packages/google-apps-card/google/apps/card_v1/__init__.py new file mode 100644 index 000000000000..e395fccb48b3 --- /dev/null +++ b/packages/google-apps-card/google/apps/card_v1/__init__.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 google.apps.card_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .types.card import ( + Action, + BorderStyle, + Button, + ButtonList, + Card, + Columns, + DateTimePicker, + DecoratedText, + Divider, + Grid, + Icon, + Image, + ImageComponent, + ImageCropStyle, + OnClick, + OpenLink, + SelectionInput, + Suggestions, + TextInput, + TextParagraph, + Widget, +) + +__all__ = ( + "Action", + "BorderStyle", + "Button", + "ButtonList", + "Card", + "Columns", + "DateTimePicker", + "DecoratedText", + "Divider", + "Grid", + "Icon", + "Image", + "ImageComponent", + "ImageCropStyle", + "OnClick", + "OpenLink", + "SelectionInput", + "Suggestions", + "TextInput", + "TextParagraph", + "Widget", +) diff --git a/packages/google-apps-card/google/apps/card_v1/gapic_metadata.json b/packages/google-apps-card/google/apps/card_v1/gapic_metadata.json new file mode 100644 index 000000000000..37ad6c64f8e7 --- /dev/null +++ b/packages/google-apps-card/google/apps/card_v1/gapic_metadata.json @@ -0,0 +1,7 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.apps.card_v1", + "protoPackage": "google.apps.card.v1", + "schema": "1.0" +} diff --git a/packages/google-apps-card/google/apps/card_v1/gapic_version.py b/packages/google-apps-card/google/apps/card_v1/gapic_version.py new file mode 100644 index 000000000000..123d60293175 --- /dev/null +++ b/packages/google-apps-card/google/apps/card_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# +__version__ = "0.1.1" # {x-release-please-version} diff --git a/packages/google-apps-card/google/apps/card_v1/py.typed b/packages/google-apps-card/google/apps/card_v1/py.typed new file mode 100644 index 000000000000..99846f9bd47e --- /dev/null +++ b/packages/google-apps-card/google/apps/card_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-apps-card package uses inline types. diff --git a/packages/google-apps-card/google/apps/card_v1/services/__init__.py b/packages/google-apps-card/google/apps/card_v1/services/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-apps-card/google/apps/card_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-apps-card/google/apps/card_v1/types/__init__.py b/packages/google-apps-card/google/apps/card_v1/types/__init__.py new file mode 100644 index 000000000000..6a3c85e0d18a --- /dev/null +++ b/packages/google-apps-card/google/apps/card_v1/types/__init__.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .card import ( + Action, + BorderStyle, + Button, + ButtonList, + Card, + Columns, + DateTimePicker, + DecoratedText, + Divider, + Grid, + Icon, + Image, + ImageComponent, + ImageCropStyle, + OnClick, + OpenLink, + SelectionInput, + Suggestions, + TextInput, + TextParagraph, + Widget, +) + +__all__ = ( + "Action", + "BorderStyle", + "Button", + "ButtonList", + "Card", + "Columns", + "DateTimePicker", + "DecoratedText", + "Divider", + "Grid", + "Icon", + "Image", + "ImageComponent", + "ImageCropStyle", + "OnClick", + "OpenLink", + "SelectionInput", + "Suggestions", + "TextInput", + "TextParagraph", + "Widget", +) diff --git a/packages/google-apps-card/google/apps/card_v1/types/card.py b/packages/google-apps-card/google/apps/card_v1/types/card.py new file mode 100644 index 000000000000..03de003dabe0 --- /dev/null +++ b/packages/google-apps-card/google/apps/card_v1/types/card.py @@ -0,0 +1,2886 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.type import color_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.apps.card.v1", + manifest={ + "Card", + "Widget", + "TextParagraph", + "Image", + "Divider", + "DecoratedText", + "TextInput", + "Suggestions", + "ButtonList", + "SelectionInput", + "DateTimePicker", + "Button", + "Icon", + "ImageCropStyle", + "BorderStyle", + "ImageComponent", + "Grid", + "Columns", + "OnClick", + "OpenLink", + "Action", + }, +) + + +class Card(proto.Message): + r"""A card interface displayed in a Google Chat message or Google + Workspace Add-on. + + Cards support a defined layout, interactive UI elements like + buttons, and rich media like images. Use cards to present detailed + information, gather information from users, and guide users to take + a next step. + + `Card builder `__ + + To learn how to build cards, see the following documentation: + + - For Google Chat apps, see `Design dynamic, interactive, and + consistent UIs with + cards `__. + - For Google Workspace Add-ons, see `Card-based + interfaces `__. + + **Example: Card message for a Google Chat app** + + |Example contact card| + + To create the sample card message in Google Chat, use the following + JSON: + + :: + + { + "cardsV2": [ + { + "cardId": "unique-card-id", + "card": { + "header": { + "title": "Sasha", + "subtitle": "Software Engineer", + "imageUrl": + "https://developers.google.com/chat/images/quickstart-app-avatar.png", + "imageType": "CIRCLE", + "imageAltText": "Avatar for Sasha", + }, + "sections": [ + { + "header": "Contact Info", + "collapsible": true, + "uncollapsibleWidgetsCount": 1, + "widgets": [ + { + "decoratedText": { + "startIcon": { + "knownIcon": "EMAIL", + }, + "text": "sasha@example.com", + } + }, + { + "decoratedText": { + "startIcon": { + "knownIcon": "PERSON", + }, + "text": "Online", + }, + }, + { + "decoratedText": { + "startIcon": { + "knownIcon": "PHONE", + }, + "text": "+1 (555) 555-1234", + } + }, + { + "buttonList": { + "buttons": [ + { + "text": "Share", + "onClick": { + "openLink": { + "url": "https://example.com/share", + } + } + }, + { + "text": "Edit", + "onClick": { + "action": { + "function": "goToView", + "parameters": [ + { + "key": "viewType", + "value": "EDIT", + } + ], + } + } + }, + ], + } + }, + ], + }, + ], + }, + } + ], + } + + .. |Example contact card| image:: https://developers.google.com/chat/images/card_api_reference.png + + Attributes: + header (google.apps.card_v1.types.Card.CardHeader): + The header of the card. A header usually + contains a leading image and a title. Headers + always appear at the top of a card. + sections (MutableSequence[google.apps.card_v1.types.Card.Section]): + Contains a collection of widgets. Each section has its own, + optional header. Sections are visually separated by a line + divider. For an example in Google Chat apps, see `Card + section `__. + section_divider_style (google.apps.card_v1.types.Card.DividerStyle): + The divider style between sections. + card_actions (MutableSequence[google.apps.card_v1.types.Card.CardAction]): + The card's actions. Actions are added to the card's toolbar + menu. + + `Google Workspace + Add-ons `__: + + For example, the following JSON constructs a card action + menu with ``Settings`` and ``Send Feedback`` options: + + :: + + "card_actions": [ + { + "actionLabel": "Settings", + "onClick": { + "action": { + "functionName": "goToView", + "parameters": [ + { + "key": "viewType", + "value": "SETTING" + } + ], + "loadIndicator": "LoadIndicator.SPINNER" + } + } + }, + { + "actionLabel": "Send Feedback", + "onClick": { + "openLink": { + "url": "https://example.com/feedback" + } + } + } + ] + name (str): + Name of the card. Used as a card identifier in card + navigation. + + `Google Workspace + Add-ons `__: + fixed_footer (google.apps.card_v1.types.Card.CardFixedFooter): + The fixed footer shown at the bottom of this card. + + Setting ``fixedFooter`` without specifying a + ``primaryButton`` or a ``secondaryButton`` causes an error. + For Chat apps, you can use fixed footers in + `dialogs `__, + but not `card + messages `__. + + `Google Workspace Add-ons and Chat + apps `__: + display_style (google.apps.card_v1.types.Card.DisplayStyle): + In Google Workspace Add-ons, sets the display properties of + the ``peekCardHeader``. + + `Google Workspace + Add-ons `__: + peek_card_header (google.apps.card_v1.types.Card.CardHeader): + When displaying contextual content, the peek card header + acts as a placeholder so that the user can navigate forward + between the homepage cards and the contextual cards. + + `Google Workspace + Add-ons `__: + """ + + class DividerStyle(proto.Enum): + r"""The divider style of a card. Currently only used for dividers + betweens card sections. + + `Google Workspace Add-ons and Chat + apps `__: + + Values: + DIVIDER_STYLE_UNSPECIFIED (0): + Don't use. Unspecified. + SOLID_DIVIDER (1): + Default option. Render a solid divider + between sections. + NO_DIVIDER (2): + If set, no divider is rendered between + sections. + """ + DIVIDER_STYLE_UNSPECIFIED = 0 + SOLID_DIVIDER = 1 + NO_DIVIDER = 2 + + class DisplayStyle(proto.Enum): + r"""In Google Workspace Add-ons, determines how a card is displayed. + + `Google Workspace + Add-ons `__: + + Values: + DISPLAY_STYLE_UNSPECIFIED (0): + Don't use. Unspecified. + PEEK (1): + The header of the card appears at the bottom + of the sidebar, partially covering the current + top card of the stack. Clicking the header pops + the card into the card stack. If the card has no + header, a generated header is used instead. + REPLACE (2): + Default value. The card is shown by replacing + the view of the top card in the card stack. + """ + DISPLAY_STYLE_UNSPECIFIED = 0 + PEEK = 1 + REPLACE = 2 + + class CardHeader(proto.Message): + r"""Represents a card header. For an example in Google Chat apps, see + `Card + header `__. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + title (str): + Required. The title of the card header. + The header has a fixed height: if both a + title and subtitle are specified, each takes up + one line. If only the title is specified, it + takes up both lines. + subtitle (str): + The subtitle of the card header. If specified, appears on + its own line below the ``title``. + image_type (google.apps.card_v1.types.Widget.ImageType): + The shape used to crop the image. + + `Google Workspace Add-ons and Chat + apps `__: + image_url (str): + The HTTPS URL of the image in the card + header. + image_alt_text (str): + The alternative text of this image that's + used for accessibility. + """ + + title: str = proto.Field( + proto.STRING, + number=1, + ) + subtitle: str = proto.Field( + proto.STRING, + number=2, + ) + image_type: "Widget.ImageType" = proto.Field( + proto.ENUM, + number=3, + enum="Widget.ImageType", + ) + image_url: str = proto.Field( + proto.STRING, + number=4, + ) + image_alt_text: str = proto.Field( + proto.STRING, + number=5, + ) + + class Section(proto.Message): + r"""A section contains a collection of widgets that are rendered + vertically in the order that they're specified. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + header (str): + Text that appears at the top of a section. Supports simple + HTML formatted text. For more information about formatting + text, see `Formatting text in Google Chat + apps `__ + and `Formatting text in Google Workspace + Add-ons `__. + widgets (MutableSequence[google.apps.card_v1.types.Widget]): + All the widgets in the section. + Must contain at least one widget. + collapsible (bool): + Indicates whether this section is collapsible. + + Collapsible sections hide some or all widgets, but users can + expand the section to reveal the hidden widgets by clicking + **Show more**. Users can hide the widgets again by clicking + **Show less**. + + To determine which widgets are hidden, specify + ``uncollapsibleWidgetsCount``. + uncollapsible_widgets_count (int): + The number of uncollapsible widgets which remain visible + even when a section is collapsed. + + For example, when a section contains five widgets and the + ``uncollapsibleWidgetsCount`` is set to ``2``, the first two + widgets are always shown and the last three are collapsed by + default. The ``uncollapsibleWidgetsCount`` is taken into + account only when ``collapsible`` is ``true``. + """ + + header: str = proto.Field( + proto.STRING, + number=1, + ) + widgets: MutableSequence["Widget"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Widget", + ) + collapsible: bool = proto.Field( + proto.BOOL, + number=5, + ) + uncollapsible_widgets_count: int = proto.Field( + proto.INT32, + number=6, + ) + + class CardAction(proto.Message): + r"""A card action is the action associated with the card. For example, + an invoice card might include actions such as delete invoice, email + invoice, or open the invoice in a browser. + + `Google Workspace + Add-ons `__: + + Attributes: + action_label (str): + The label that displays as the action menu + item. + on_click (google.apps.card_v1.types.OnClick): + The ``onClick`` action for this action item. + """ + + action_label: str = proto.Field( + proto.STRING, + number=1, + ) + on_click: "OnClick" = proto.Field( + proto.MESSAGE, + number=2, + message="OnClick", + ) + + class CardFixedFooter(proto.Message): + r"""A persistent (sticky) footer that that appears at the bottom of the + card. + + Setting ``fixedFooter`` without specifying a ``primaryButton`` or a + ``secondaryButton`` causes an error. + + For Chat apps, you can use fixed footers in + `dialogs `__, + but not `card + messages `__. + For an example in Google Chat apps, see `Card + footer `__. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + primary_button (google.apps.card_v1.types.Button): + The primary button of the fixed footer. The + button must be a text button with text and color + set. + secondary_button (google.apps.card_v1.types.Button): + The secondary button of the fixed footer. The button must be + a text button with text and color set. If + ``secondaryButton`` is set, you must also set + ``primaryButton``. + """ + + primary_button: "Button" = proto.Field( + proto.MESSAGE, + number=1, + message="Button", + ) + secondary_button: "Button" = proto.Field( + proto.MESSAGE, + number=2, + message="Button", + ) + + header: CardHeader = proto.Field( + proto.MESSAGE, + number=1, + message=CardHeader, + ) + sections: MutableSequence[Section] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Section, + ) + section_divider_style: DividerStyle = proto.Field( + proto.ENUM, + number=9, + enum=DividerStyle, + ) + card_actions: MutableSequence[CardAction] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=CardAction, + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + fixed_footer: CardFixedFooter = proto.Field( + proto.MESSAGE, + number=5, + message=CardFixedFooter, + ) + display_style: DisplayStyle = proto.Field( + proto.ENUM, + number=6, + enum=DisplayStyle, + ) + peek_card_header: CardHeader = proto.Field( + proto.MESSAGE, + number=7, + message=CardHeader, + ) + + +class Widget(proto.Message): + r"""Each card is made up of widgets. + + A widget is a composite object that can represent one of text, + images, buttons, and other object types. + + 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: + text_paragraph (google.apps.card_v1.types.TextParagraph): + Displays a text paragraph. Supports simple HTML formatted + text. For more information about formatting text, see + `Formatting text in Google Chat + apps `__ + and `Formatting text in Google Workspace + Add-ons `__. + + For example, the following JSON creates a bolded text: + + :: + + "textParagraph": { + "text": " bold text" + } + + This field is a member of `oneof`_ ``data``. + image (google.apps.card_v1.types.Image): + Displays an image. + + For example, the following JSON creates an image with + alternative text: + + :: + + "image": { + "imageUrl": + "https://developers.google.com/chat/images/quickstart-app-avatar.png", + "altText": "Chat app avatar" + } + + This field is a member of `oneof`_ ``data``. + decorated_text (google.apps.card_v1.types.DecoratedText): + Displays a decorated text item. + + For example, the following JSON creates a decorated text + widget showing email address: + + :: + + "decoratedText": { + "icon": { + "knownIcon": "EMAIL" + }, + "topLabel": "Email Address", + "text": "sasha@example.com", + "bottomLabel": "This is a new Email address!", + "switchControl": { + "name": "has_send_welcome_email_to_sasha", + "selected": false, + "controlType": "CHECKBOX" + } + } + + This field is a member of `oneof`_ ``data``. + button_list (google.apps.card_v1.types.ButtonList): + A list of buttons. + + For example, the following JSON creates two buttons. The + first is a blue text button and the second is an image + button that opens a link: + + :: + + "buttonList": { + "buttons": [ + { + "text": "Edit", + "color": { + "red": 0, + "green": 0, + "blue": 1, + "alpha": 1 + }, + "disabled": true, + }, + { + "icon": { + "knownIcon": "INVITE", + "altText": "check calendar" + }, + "onClick": { + "openLink": { + "url": "https://example.com/calendar" + } + } + } + ] + } + + This field is a member of `oneof`_ ``data``. + text_input (google.apps.card_v1.types.TextInput): + Displays a text box that users can type into. + + For example, the following JSON creates a text input for an + email address: + + :: + + "textInput": { + "name": "mailing_address", + "label": "Mailing Address" + } + + As another example, the following JSON creates a text input + for a programming language with static suggestions: + + :: + + "textInput": { + "name": "preferred_programing_language", + "label": "Preferred Language", + "initialSuggestions": { + "items": [ + { + "text": "C++" + }, + { + "text": "Java" + }, + { + "text": "JavaScript" + }, + { + "text": "Python" + } + ] + } + } + + This field is a member of `oneof`_ ``data``. + selection_input (google.apps.card_v1.types.SelectionInput): + Displays a selection control that lets users select items. + Selection controls can be checkboxes, radio buttons, + switches, or dropdown menus. + + For example, the following JSON creates a dropdown menu that + lets users choose a size: + + :: + + "selectionInput": { + "name": "size", + "label": "Size" + "type": "DROPDOWN", + "items": [ + { + "text": "S", + "value": "small", + "selected": false + }, + { + "text": "M", + "value": "medium", + "selected": true + }, + { + "text": "L", + "value": "large", + "selected": false + }, + { + "text": "XL", + "value": "extra_large", + "selected": false + } + ] + } + + This field is a member of `oneof`_ ``data``. + date_time_picker (google.apps.card_v1.types.DateTimePicker): + Displays a widget that lets users input a date, time, or + date and time. + + For example, the following JSON creates a date time picker + to schedule an appointment: + + :: + + "dateTimePicker": { + "name": "appointment_time", + "label": "Book your appointment at:", + "type": "DATE_AND_TIME", + "valueMsEpoch": "796435200000" + } + + This field is a member of `oneof`_ ``data``. + divider (google.apps.card_v1.types.Divider): + Displays a horizontal line divider between widgets. + + For example, the following JSON creates a divider: + + :: + + "divider": { + } + + This field is a member of `oneof`_ ``data``. + grid (google.apps.card_v1.types.Grid): + Displays a grid with a collection of items. + + A grid supports any number of columns and items. The number + of rows is determined by the upper bounds of the number + items divided by the number of columns. A grid with 10 items + and 2 columns has 5 rows. A grid with 11 items and 2 columns + has 6 rows. + + `Google Workspace Add-ons and Chat + apps `__: + + For example, the following JSON creates a 2 column grid with + a single item: + + :: + + "grid": { + "title": "A fine collection of items", + "columnCount": 2, + "borderStyle": { + "type": "STROKE", + "cornerRadius": 4 + }, + "items": [ + { + "image": { + "imageUri": "https://www.example.com/image.png", + "cropStyle": { + "type": "SQUARE" + }, + "borderStyle": { + "type": "STROKE" + } + }, + "title": "An item", + "textAlignment": "CENTER" + } + ], + "onClick": { + "openLink": { + "url": "https://www.example.com" + } + } + } + + This field is a member of `oneof`_ ``data``. + columns (google.apps.card_v1.types.Columns): + Displays up to 2 columns. + + To include more than 2 columns, or to use rows, use the + ``Grid`` widget. + + For example, the following JSON creates 2 columns that each + contain text paragraphs: + + :: + + "columns": { + "columnItems": [ + { + "horizontalSizeStyle": "FILL_AVAILABLE_SPACE", + "horizontalAlignment": "CENTER", + "verticalAlignment": "CENTER", + "widgets": [ + { + "textParagraph": { + "text": "First column text paragraph" + } + } + ] + }, + { + "horizontalSizeStyle": "FILL_AVAILABLE_SPACE", + "horizontalAlignment": "CENTER", + "verticalAlignment": "CENTER", + "widgets": [ + { + "textParagraph": { + "text": "Second column text paragraph" + } + } + ] + } + ] + } + + This field is a member of `oneof`_ ``data``. + horizontal_alignment (google.apps.card_v1.types.Widget.HorizontalAlignment): + Specifies whether widgets align to the left, + right, or center of a column. + """ + + class ImageType(proto.Enum): + r"""The shape used to crop the image. + + `Google Workspace Add-ons and Chat + apps `__: + + Values: + SQUARE (0): + Default value. Applies a square mask to the + image. For example, a 4x3 image becomes 3x3. + CIRCLE (1): + Applies a circular mask to the image. For + example, a 4x3 image becomes a circle with a + diameter of 3. + """ + SQUARE = 0 + CIRCLE = 1 + + class HorizontalAlignment(proto.Enum): + r"""Specifies whether widgets align to the left, right, or center of a + column. + + `Google Chat apps `__: + + Values: + HORIZONTAL_ALIGNMENT_UNSPECIFIED (0): + Don't use. Unspecified. + START (1): + Default value. Aligns widgets to the start + position of the column. For left-to-right + layouts, aligns to the left. For right-to-left + layouts, aligns to the right. + CENTER (2): + Aligns widgets to the center of the column. + END (3): + Aligns widgets to the end position of the + column. For left-to-right layouts, aligns + widgets to the right. For right-to-left layouts, + aligns widgets to the left. + """ + HORIZONTAL_ALIGNMENT_UNSPECIFIED = 0 + START = 1 + CENTER = 2 + END = 3 + + text_paragraph: "TextParagraph" = proto.Field( + proto.MESSAGE, + number=1, + oneof="data", + message="TextParagraph", + ) + image: "Image" = proto.Field( + proto.MESSAGE, + number=2, + oneof="data", + message="Image", + ) + decorated_text: "DecoratedText" = proto.Field( + proto.MESSAGE, + number=3, + oneof="data", + message="DecoratedText", + ) + button_list: "ButtonList" = proto.Field( + proto.MESSAGE, + number=4, + oneof="data", + message="ButtonList", + ) + text_input: "TextInput" = proto.Field( + proto.MESSAGE, + number=5, + oneof="data", + message="TextInput", + ) + selection_input: "SelectionInput" = proto.Field( + proto.MESSAGE, + number=6, + oneof="data", + message="SelectionInput", + ) + date_time_picker: "DateTimePicker" = proto.Field( + proto.MESSAGE, + number=7, + oneof="data", + message="DateTimePicker", + ) + divider: "Divider" = proto.Field( + proto.MESSAGE, + number=9, + oneof="data", + message="Divider", + ) + grid: "Grid" = proto.Field( + proto.MESSAGE, + number=10, + oneof="data", + message="Grid", + ) + columns: "Columns" = proto.Field( + proto.MESSAGE, + number=11, + oneof="data", + message="Columns", + ) + horizontal_alignment: HorizontalAlignment = proto.Field( + proto.ENUM, + number=8, + enum=HorizontalAlignment, + ) + + +class TextParagraph(proto.Message): + r"""A paragraph of text that supports formatting. For an example in + Google Chat apps, see `Text + paragraph `__. + For more information about formatting text, see `Formatting text in + Google Chat + apps `__ + and `Formatting text in Google Workspace + Add-ons `__. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + text (str): + The text that's shown in the widget. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + ) + + +class Image(proto.Message): + r"""An image that is specified by a URL and can have an ``onClick`` + action. For an example, see + `Image `__. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + image_url (str): + The HTTPS URL that hosts the image. + + For example: + + :: + + https://developers.google.com/chat/images/quickstart-app-avatar.png + on_click (google.apps.card_v1.types.OnClick): + When a user clicks the image, the click + triggers this action. + alt_text (str): + The alternative text of this image that's + used for accessibility. + """ + + image_url: str = proto.Field( + proto.STRING, + number=1, + ) + on_click: "OnClick" = proto.Field( + proto.MESSAGE, + number=2, + message="OnClick", + ) + alt_text: str = proto.Field( + proto.STRING, + number=3, + ) + + +class Divider(proto.Message): + r"""Displays a divider between widgets as a horizontal line. For an + example in Google Chat apps, see + `Divider `__. + + `Google Workspace Add-ons and Chat + apps `__: + + For example, the following JSON creates a divider: + + :: + + "divider": {} + + """ + + +class DecoratedText(proto.Message): + r"""A widget that displays text with optional decorations such as a + label above or below the text, an icon in front of the text, a + selection widget, or a button after the text. For an example in + Google Chat apps, see `Decorated + text `__. + + `Google Workspace Add-ons and Chat + apps `__: + + 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: + icon (google.apps.card_v1.types.Icon): + Deprecated in favor of ``startIcon``. + start_icon (google.apps.card_v1.types.Icon): + The icon displayed in front of the text. + top_label (str): + The text that appears above ``text``. Always truncates. + text (str): + Required. The primary text. + + Supports simple formatting. For more information about + formatting text, see `Formatting text in Google Chat + apps `__ + and `Formatting text in Google Workspace + Add-ons `__. + wrap_text (bool): + The wrap text setting. If ``true``, the text wraps and + displays on multiple lines. Otherwise, the text is + truncated. + + Only applies to ``text``, not ``topLabel`` and + ``bottomLabel``. + bottom_label (str): + The text that appears below ``text``. Always wraps. + on_click (google.apps.card_v1.types.OnClick): + This action is triggered when users click ``topLabel`` or + ``bottomLabel``. + button (google.apps.card_v1.types.Button): + A button that a user can click to trigger an + action. + + This field is a member of `oneof`_ ``control``. + switch_control (google.apps.card_v1.types.DecoratedText.SwitchControl): + A switch widget that a user can click to + change its state and trigger an action. + + This field is a member of `oneof`_ ``control``. + end_icon (google.apps.card_v1.types.Icon): + An icon displayed after the text. + + Supports + `built-in `__ + and + `custom `__ + icons. + + This field is a member of `oneof`_ ``control``. + """ + + class SwitchControl(proto.Message): + r"""Either a toggle-style switch or a checkbox inside a + ``decoratedText`` widget. + + `Google Workspace Add-ons and Chat + apps `__: + + Only supported in the ``decoratedText`` widget. + + Attributes: + name (str): + The name by which the switch widget is identified in a form + input event. + + For details about working with form inputs, see `Receive + form + data `__. + value (str): + The value entered by a user, returned as part of a form + input event. + + For details about working with form inputs, see `Receive + form + data `__. + selected (bool): + When ``true``, the switch is selected. + on_change_action (google.apps.card_v1.types.Action): + The action to perform when the switch state + is changed, such as what function to run. + control_type (google.apps.card_v1.types.DecoratedText.SwitchControl.ControlType): + How the switch appears in the user interface. + + `Google Workspace Add-ons and Chat + apps `__: + """ + + class ControlType(proto.Enum): + r"""How the switch appears in the user interface. + + `Google Workspace Add-ons and Chat + apps `__: + + Values: + SWITCH (0): + A toggle-style switch. + CHECKBOX (1): + Deprecated in favor of ``CHECK_BOX``. + CHECK_BOX (2): + A checkbox. + """ + SWITCH = 0 + CHECKBOX = 1 + CHECK_BOX = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + selected: bool = proto.Field( + proto.BOOL, + number=3, + ) + on_change_action: "Action" = proto.Field( + proto.MESSAGE, + number=4, + message="Action", + ) + control_type: "DecoratedText.SwitchControl.ControlType" = proto.Field( + proto.ENUM, + number=5, + enum="DecoratedText.SwitchControl.ControlType", + ) + + icon: "Icon" = proto.Field( + proto.MESSAGE, + number=1, + message="Icon", + ) + start_icon: "Icon" = proto.Field( + proto.MESSAGE, + number=12, + message="Icon", + ) + top_label: str = proto.Field( + proto.STRING, + number=3, + ) + text: str = proto.Field( + proto.STRING, + number=4, + ) + wrap_text: bool = proto.Field( + proto.BOOL, + number=5, + ) + bottom_label: str = proto.Field( + proto.STRING, + number=6, + ) + on_click: "OnClick" = proto.Field( + proto.MESSAGE, + number=7, + message="OnClick", + ) + button: "Button" = proto.Field( + proto.MESSAGE, + number=8, + oneof="control", + message="Button", + ) + switch_control: SwitchControl = proto.Field( + proto.MESSAGE, + number=9, + oneof="control", + message=SwitchControl, + ) + end_icon: "Icon" = proto.Field( + proto.MESSAGE, + number=11, + oneof="control", + message="Icon", + ) + + +class TextInput(proto.Message): + r"""A field in which users can enter text. Supports suggestions and + on-change actions. For an example in Google Chat apps, see `Text + input `__. + + Chat apps receive and can process the value of entered text during + form input events. For details about working with form inputs, see + `Receive form + data `__. + + When you need to collect undefined or abstract data from users, use + a text input. To collect defined or enumerated data from users, use + the [SelectionInput][google.apps.card.v1.SelectionInput] widget. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + name (str): + The name by which the text input is identified in a form + input event. + + For details about working with form inputs, see `Receive + form + data `__. + label (str): + The text that appears above the text input field in the user + interface. + + Specify text that helps the user enter the information your + app needs. For example, if you are asking someone's name, + but specifically need their surname, write ``surname`` + instead of ``name``. + + Required if ``hintText`` is unspecified. Otherwise, + optional. + hint_text (str): + Text that appears below the text input field meant to assist + users by prompting them to enter a certain value. This text + is always visible. + + Required if ``label`` is unspecified. Otherwise, optional. + value (str): + The value entered by a user, returned as part of a form + input event. + + For details about working with form inputs, see `Receive + form + data `__. + type_ (google.apps.card_v1.types.TextInput.Type): + How a text input field appears in the user + interface. For example, whether the field is + single or multi-line. + on_change_action (google.apps.card_v1.types.Action): + What to do when a change occurs in the text input field. For + example, a user adding to the field or deleting text. + + Examples of actions to take include running a custom + function or opening a + `dialog `__ + in Google Chat. + initial_suggestions (google.apps.card_v1.types.Suggestions): + Suggested values that users can enter. These values appear + when users click inside the text input field. As users type, + the suggested values dynamically filter to match what the + users have typed. + + For example, a text input field for programming language + might suggest Java, JavaScript, Python, and C++. When users + start typing ``Jav``, the list of suggestions filters to + show just ``Java`` and ``JavaScript``. + + Suggested values help guide users to enter values that your + app can make sense of. When referring to JavaScript, some + users might enter ``javascript`` and others ``java script``. + Suggesting ``JavaScript`` can standardize how users interact + with your app. + + When specified, ``TextInput.type`` is always + ``SINGLE_LINE``, even if it's set to ``MULTIPLE_LINE``. + + `Google Workspace Add-ons and Chat + apps `__: + auto_complete_action (google.apps.card_v1.types.Action): + Optional. Specify what action to take when the text input + field provides suggestions to users who interact with it. + + If unspecified, the suggestions are set by + ``initialSuggestions`` and are processed by the client. + + If specified, the app takes the action specified here, such + as running a custom function. + + `Google Workspace + Add-ons `__: + placeholder_text (str): + Text that appears in the text input field when the field is + empty. Use this text to prompt users to enter a value. For + example, ``Enter a number from 0 to 100``. + + `Google Chat apps `__: + """ + + class Type(proto.Enum): + r"""How a text input field appears in the user interface. For example, + whether it's a single line input field, or a multi-line input. If + ``initialSuggestions`` is specified, ``type`` is always + ``SINGLE_LINE``, even if it's set to ``MULTIPLE_LINE``. + + `Google Workspace Add-ons and Chat + apps `__: + + Values: + SINGLE_LINE (0): + The text input field has a fixed height of + one line. + MULTIPLE_LINE (1): + The text input field has a fixed height of + multiple lines. + """ + SINGLE_LINE = 0 + MULTIPLE_LINE = 1 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + label: str = proto.Field( + proto.STRING, + number=2, + ) + hint_text: str = proto.Field( + proto.STRING, + number=3, + ) + value: str = proto.Field( + proto.STRING, + number=4, + ) + type_: Type = proto.Field( + proto.ENUM, + number=5, + enum=Type, + ) + on_change_action: "Action" = proto.Field( + proto.MESSAGE, + number=6, + message="Action", + ) + initial_suggestions: "Suggestions" = proto.Field( + proto.MESSAGE, + number=7, + message="Suggestions", + ) + auto_complete_action: "Action" = proto.Field( + proto.MESSAGE, + number=8, + message="Action", + ) + placeholder_text: str = proto.Field( + proto.STRING, + number=12, + ) + + +class Suggestions(proto.Message): + r"""Suggested values that users can enter. These values appear when + users click inside the text input field. As users type, the + suggested values dynamically filter to match what the users have + typed. + + For example, a text input field for programming language might + suggest Java, JavaScript, Python, and C++. When users start typing + ``Jav``, the list of suggestions filters to show ``Java`` and + ``JavaScript``. + + Suggested values help guide users to enter values that your app can + make sense of. When referring to JavaScript, some users might enter + ``javascript`` and others ``java script``. Suggesting ``JavaScript`` + can standardize how users interact with your app. + + When specified, ``TextInput.type`` is always ``SINGLE_LINE``, even + if it's set to ``MULTIPLE_LINE``. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + items (MutableSequence[google.apps.card_v1.types.Suggestions.SuggestionItem]): + A list of suggestions used for autocomplete + recommendations in text input fields. + """ + + class SuggestionItem(proto.Message): + r"""One suggested value that users can enter in a text input field. + + `Google Workspace Add-ons and Chat + apps `__: + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text (str): + The value of a suggested input to a text + input field. This is equivalent to what users + enter themselves. + + This field is a member of `oneof`_ ``content``. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + oneof="content", + ) + + items: MutableSequence[SuggestionItem] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SuggestionItem, + ) + + +class ButtonList(proto.Message): + r"""A list of buttons layed out horizontally. For an example in Google + Chat apps, see `Button + list `__. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + buttons (MutableSequence[google.apps.card_v1.types.Button]): + An array of buttons. + """ + + buttons: MutableSequence["Button"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Button", + ) + + +class SelectionInput(proto.Message): + r"""A widget that creates one or more UI items that users can select. + For example, a dropdown menu or checkboxes. You can use this widget + to collect data that can be predicted or enumerated. For an example + in Google Chat apps, see `Selection + input `__. + + Chat apps can process the value of items that users select or input. + For details about working with form inputs, see `Receive form + data `__. + + To collect undefined or abstract data from users, use the + [TextInput][google.apps.card.v1.TextInput] widget. + + `Google Workspace Add-ons and Chat + apps `__: + + 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: + name (str): + The name that identifies the selection input in a form input + event. + + For details about working with form inputs, see `Receive + form + data `__. + label (str): + The text that appears above the selection + input field in the user interface. + + Specify text that helps the user enter the + information your app needs. For example, if + users are selecting the urgency of a work ticket + from a drop-down menu, the label might be + "Urgency" or "Select urgency". + type_ (google.apps.card_v1.types.SelectionInput.SelectionType): + The type of items that are displayed to users in a + ``SelectionInput`` widget. Selection types support different + types of interactions. For example, users can select one or + more checkboxes, but they can only select one value from a + dropdown menu. + items (MutableSequence[google.apps.card_v1.types.SelectionInput.SelectionItem]): + An array of selectable items. For example, an + array of radio buttons or checkboxes. Supports + up to 100 items. + on_change_action (google.apps.card_v1.types.Action): + If specified, the form is submitted when the selection + changes. If not specified, you must specify a separate + button that submits the form. + + For details about working with form inputs, see `Receive + form + data `__. + multi_select_max_selected_items (int): + For multiselect menus, the maximum number of + items that a user can select. Minimum value is 1 + item. If unspecified, defaults to 3 items. + multi_select_min_query_length (int): + For multiselect menus, the number of text + characters that a user inputs before the Chat + app queries autocomplete and displays suggested + items in the menu. + + If unspecified, defaults to 0 characters for + static data sources and 3 characters for + external data sources. + external_data_source (google.apps.card_v1.types.Action): + An external data source, such as a relational + data base. + + This field is a member of `oneof`_ ``multi_select_data_source``. + platform_data_source (google.apps.card_v1.types.SelectionInput.PlatformDataSource): + A data source from Google Workspace. + + This field is a member of `oneof`_ ``multi_select_data_source``. + """ + + class SelectionType(proto.Enum): + r"""The format for the items that users can select. Different options + support different types of interactions. For example, users can + select multiple checkboxes, but can only select one item from a + dropdown menu. + + Each selection input supports one type of selection. Mixing + checkboxes and switches, for example, isn't supported. + + `Google Workspace Add-ons and Chat + apps `__: + + Values: + CHECK_BOX (0): + A set of checkboxes. Users can select one or + more checkboxes. + RADIO_BUTTON (1): + A set of radio buttons. Users can select one + radio button. + SWITCH (2): + A set of switches. Users can turn on one or + more switches. + DROPDOWN (3): + A dropdown menu. Users can select one item + from the menu. + MULTI_SELECT (4): + A multiselect menu for static or dynamic data. From the menu + bar, users select one or more items. Users can also input + values to populate dynamic data. For example, users can + start typing the name of a Google Chat space and the widget + autosuggests the space. + + To populate items for a multiselect menu, you can use one of + the following types of data sources: + + - Static data: Items are specified as ``SelectionItem`` + objects in the widget. Up to 100 items. + - Google Workspace data: Items are populated using data + from Google Workspace, such as Google Workspace users or + Google Chat spaces. + - External data: Items are populated from an external data + source outside of Google Workspace. + + For examples of how to implement multiselect menus, see the + ```SelectionInput`` widget + page `__. + + `Google Workspace Add-ons and Chat + apps `__: + multiselect for Google Workspace Add-ons are in `Developer + Preview `__. + """ + CHECK_BOX = 0 + RADIO_BUTTON = 1 + SWITCH = 2 + DROPDOWN = 3 + MULTI_SELECT = 4 + + class SelectionItem(proto.Message): + r"""An item that users can select in a selection input, such as a + checkbox or switch. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + text (str): + The text that identifies or describes the + item to users. + value (str): + The value associated with this item. The client should use + this as a form input value. + + For details about working with form inputs, see `Receive + form + data `__. + selected (bool): + Whether the item is selected by default. If + the selection input only accepts one value (such + as for radio buttons or a dropdown menu), only + set this field for one item. + start_icon_uri (str): + For multiselect menus, the URL for the icon displayed next + to the item's ``text`` field. Supports PNG and JPEG files. + Must be an ``HTTPS`` URL. For example, + ``https://developers.google.com/chat/images/quickstart-app-avatar.png``. + bottom_text (str): + For multiselect menus, a text description or label that's + displayed below the item's ``text`` field. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + selected: bool = proto.Field( + proto.BOOL, + number=3, + ) + start_icon_uri: str = proto.Field( + proto.STRING, + number=4, + ) + bottom_text: str = proto.Field( + proto.STRING, + number=5, + ) + + class PlatformDataSource(proto.Message): + r"""For a [``SelectionInput``][google.apps.card.v1.SelectionInput] + widget that uses a multiselect menu, a data source from Google + Workspace. Used to populate items in a multiselect menu. + + `Google Chat apps `__: + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + common_data_source (google.apps.card_v1.types.SelectionInput.PlatformDataSource.CommonDataSource): + A data source shared by all Google Workspace + applications, such as users in a Google + Workspace organization. + + This field is a member of `oneof`_ ``data_source``. + """ + + class CommonDataSource(proto.Enum): + r"""A data source shared by all [Google Workspace applications] + (https://developers.google.com/chat/api/reference/rest/v1/HostApp). + + `Google Chat apps `__: + + Values: + UNKNOWN (0): + Default value. Don't use. + USER (1): + Google Workspace users. The user can only + view and select users from their Google + Workspace organization. + """ + UNKNOWN = 0 + USER = 1 + + common_data_source: "SelectionInput.PlatformDataSource.CommonDataSource" = ( + proto.Field( + proto.ENUM, + number=1, + oneof="data_source", + enum="SelectionInput.PlatformDataSource.CommonDataSource", + ) + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + label: str = proto.Field( + proto.STRING, + number=2, + ) + type_: SelectionType = proto.Field( + proto.ENUM, + number=3, + enum=SelectionType, + ) + items: MutableSequence[SelectionItem] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=SelectionItem, + ) + on_change_action: "Action" = proto.Field( + proto.MESSAGE, + number=5, + message="Action", + ) + multi_select_max_selected_items: int = proto.Field( + proto.INT32, + number=6, + ) + multi_select_min_query_length: int = proto.Field( + proto.INT32, + number=7, + ) + external_data_source: "Action" = proto.Field( + proto.MESSAGE, + number=8, + oneof="multi_select_data_source", + message="Action", + ) + platform_data_source: PlatformDataSource = proto.Field( + proto.MESSAGE, + number=9, + oneof="multi_select_data_source", + message=PlatformDataSource, + ) + + +class DateTimePicker(proto.Message): + r"""Lets users input a date, a time, or both a date and a time. For an + example in Google Chat apps, see `Date time + picker `__. + + Users can input text or use the picker to select dates and times. If + users input an invalid date or time, the picker shows an error that + prompts users to input the information correctly. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + name (str): + The name by which the ``DateTimePicker`` is identified in a + form input event. + + For details about working with form inputs, see `Receive + form + data `__. + label (str): + The text that prompts users to input a date, a time, or a + date and time. For example, if users are scheduling an + appointment, use a label such as ``Appointment date`` or + ``Appointment date and time``. + type_ (google.apps.card_v1.types.DateTimePicker.DateTimePickerType): + Whether the widget supports inputting a date, + a time, or the date and time. + value_ms_epoch (int): + The default value displayed in the widget, in milliseconds + since `Unix epoch + time `__. + + Specify the value based on the type of picker + (``DateTimePickerType``): + + - ``DATE_AND_TIME``: a calendar date and time in UTC. For + example, to represent January 1, 2023 at 12:00 PM UTC, + use ``1672574400000``. + - ``DATE_ONLY``: a calendar date at 00:00:00 UTC. For + example, to represent January 1, 2023, use + ``1672531200000``. + - ``TIME_ONLY``: a time in UTC. For example, to represent + 12:00 PM, use ``43200000`` (or ``12 * 60 * 60 * 1000``). + timezone_offset_date (int): + The number representing the time zone offset from UTC, in + minutes. If set, the ``value_ms_epoch`` is displayed in the + specified time zone. If unset, the value defaults to the + user's time zone setting. + on_change_action (google.apps.card_v1.types.Action): + Triggered when the user clicks **Save** or **Clear** from + the ``DateTimePicker`` interface. + """ + + class DateTimePickerType(proto.Enum): + r"""The format for the date and time in the ``DateTimePicker`` widget. + Determines whether users can input a date, a time, or both a date + and time. + + `Google Workspace Add-ons and Chat + apps `__: + + Values: + DATE_AND_TIME (0): + Users input a date and time. + DATE_ONLY (1): + Users input a date. + TIME_ONLY (2): + Users input a time. + """ + DATE_AND_TIME = 0 + DATE_ONLY = 1 + TIME_ONLY = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + label: str = proto.Field( + proto.STRING, + number=2, + ) + type_: DateTimePickerType = proto.Field( + proto.ENUM, + number=3, + enum=DateTimePickerType, + ) + value_ms_epoch: int = proto.Field( + proto.INT64, + number=4, + ) + timezone_offset_date: int = proto.Field( + proto.INT32, + number=5, + ) + on_change_action: "Action" = proto.Field( + proto.MESSAGE, + number=6, + message="Action", + ) + + +class Button(proto.Message): + r"""A text, icon, or text and icon button that users can click. For an + example in Google Chat apps, see `Button + list `__. + + To make an image a clickable button, specify an + [``Image``][google.apps.card.v1.Image] (not an + [``ImageComponent``][google.apps.card.v1.ImageComponent]) and set an + ``onClick`` action. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + text (str): + The text displayed inside the button. + icon (google.apps.card_v1.types.Icon): + The icon image. If both ``icon`` and ``text`` are set, then + the icon appears before the text. + color (google.type.color_pb2.Color): + If set, the button is filled with a solid background color + and the font color changes to maintain contrast with the + background color. For example, setting a blue background + likely results in white text. + + If unset, the image background is white and the font color + is blue. + + For red, green, and blue, the value of each field is a + ``float`` number that you can express in either of two ways: + as a number between 0 and 255 divided by 255 (153/255), or + as a value between 0 and 1 (0.6). 0 represents the absence + of a color and 1 or 255/255 represent the full presence of + that color on the RGB scale. + + Optionally set ``alpha``, which sets a level of transparency + using this equation: + + :: + + pixel color = alpha * (this color) + (1.0 - alpha) * (background color) + + For ``alpha``, a value of ``1`` corresponds with a solid + color, and a value of ``0`` corresponds with a completely + transparent color. + + For example, the following color represents a half + transparent red: + + :: + + "color": { + "red": 1, + "green": 0, + "blue": 0, + "alpha": 0.5 + } + on_click (google.apps.card_v1.types.OnClick): + Required. The action to perform when a user + clicks the button, such as opening a hyperlink + or running a custom function. + disabled (bool): + If ``true``, the button is displayed in an inactive state + and doesn't respond to user actions. + alt_text (str): + The alternative text that's used for + accessibility. + Set descriptive text that lets users know what + the button does. For example, if a button opens + a hyperlink, you might write: "Opens a new + browser tab and navigates to the Google Chat + developer documentation at + https://developers.google.com/chat". + """ + + text: str = proto.Field( + proto.STRING, + number=1, + ) + icon: "Icon" = proto.Field( + proto.MESSAGE, + number=2, + message="Icon", + ) + color: color_pb2.Color = proto.Field( + proto.MESSAGE, + number=3, + message=color_pb2.Color, + ) + on_click: "OnClick" = proto.Field( + proto.MESSAGE, + number=4, + message="OnClick", + ) + disabled: bool = proto.Field( + proto.BOOL, + number=5, + ) + alt_text: str = proto.Field( + proto.STRING, + number=6, + ) + + +class Icon(proto.Message): + r"""An icon displayed in a widget on a card. For an example in Google + Chat apps, see + `Icon `__. + + Supports + `built-in `__ + and + `custom `__ + icons. + + `Google Workspace Add-ons and Chat + apps `__: + + 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: + known_icon (str): + Display one of the built-in icons provided by Google + Workspace. + + For example, to display an airplane icon, specify + ``AIRPLANE``. For a bus, specify ``BUS``. + + For a full list of supported icons, see `built-in + icons `__. + + This field is a member of `oneof`_ ``icons``. + icon_url (str): + Display a custom icon hosted at an HTTPS URL. + + For example: + + :: + + "iconUrl": + "https://developers.google.com/chat/images/quickstart-app-avatar.png" + + Supported file types include ``.png`` and ``.jpg``. + + This field is a member of `oneof`_ ``icons``. + alt_text (str): + Optional. A description of the icon used for accessibility. + If unspecified, the default value ``Button`` is provided. As + a best practice, you should set a helpful description for + what the icon displays, and if applicable, what it does. For + example, ``A user's account portrait``, or + ``Opens a new browser tab and navigates to the Google Chat developer documentation at https://developers.google.com/chat``. + + If the icon is set in a + [``Button``][google.apps.card.v1.Button], the ``altText`` + appears as helper text when the user hovers over the button. + However, if the button also sets ``text``, the icon's + ``altText`` is ignored. + image_type (google.apps.card_v1.types.Widget.ImageType): + The crop style applied to the image. In some cases, applying + a ``CIRCLE`` crop causes the image to be drawn larger than a + built-in icon. + """ + + known_icon: str = proto.Field( + proto.STRING, + number=1, + oneof="icons", + ) + icon_url: str = proto.Field( + proto.STRING, + number=2, + oneof="icons", + ) + alt_text: str = proto.Field( + proto.STRING, + number=3, + ) + image_type: "Widget.ImageType" = proto.Field( + proto.ENUM, + number=4, + enum="Widget.ImageType", + ) + + +class ImageCropStyle(proto.Message): + r"""Represents the crop style applied to an image. + + `Google Workspace Add-ons and Chat + apps `__: + + For example, here's how to apply a 16:9 aspect ratio: + + :: + + cropStyle { + "type": "RECTANGLE_CUSTOM", + "aspectRatio": 16/9 + } + + Attributes: + type_ (google.apps.card_v1.types.ImageCropStyle.ImageCropType): + The crop type. + aspect_ratio (float): + The aspect ratio to use if the crop type is + ``RECTANGLE_CUSTOM``. + + For example, here's how to apply a 16:9 aspect ratio: + + :: + + cropStyle { + "type": "RECTANGLE_CUSTOM", + "aspectRatio": 16/9 + } + """ + + class ImageCropType(proto.Enum): + r"""Represents the crop style applied to an image. + + `Google Workspace Add-ons and Chat + apps `__: + + Values: + IMAGE_CROP_TYPE_UNSPECIFIED (0): + Don't use. Unspecified. + SQUARE (1): + Default value. Applies a square crop. + CIRCLE (2): + Applies a circular crop. + RECTANGLE_CUSTOM (3): + Applies a rectangular crop with a custom aspect ratio. Set + the custom aspect ratio with ``aspectRatio``. + RECTANGLE_4_3 (4): + Applies a rectangular crop with a 4:3 aspect + ratio. + """ + IMAGE_CROP_TYPE_UNSPECIFIED = 0 + SQUARE = 1 + CIRCLE = 2 + RECTANGLE_CUSTOM = 3 + RECTANGLE_4_3 = 4 + + type_: ImageCropType = proto.Field( + proto.ENUM, + number=1, + enum=ImageCropType, + ) + aspect_ratio: float = proto.Field( + proto.DOUBLE, + number=2, + ) + + +class BorderStyle(proto.Message): + r"""The style options for the border of a card or widget, including the + border type and color. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + type_ (google.apps.card_v1.types.BorderStyle.BorderType): + The border type. + stroke_color (google.type.color_pb2.Color): + The colors to use when the type is ``BORDER_TYPE_STROKE``. + corner_radius (int): + The corner radius for the border. + """ + + class BorderType(proto.Enum): + r"""Represents the border types applied to widgets. + + `Google Workspace Add-ons and Chat + apps `__: + + Values: + BORDER_TYPE_UNSPECIFIED (0): + Don't use. Unspecified. + NO_BORDER (1): + Default value. No border. + STROKE (2): + Outline. + """ + BORDER_TYPE_UNSPECIFIED = 0 + NO_BORDER = 1 + STROKE = 2 + + type_: BorderType = proto.Field( + proto.ENUM, + number=1, + enum=BorderType, + ) + stroke_color: color_pb2.Color = proto.Field( + proto.MESSAGE, + number=2, + message=color_pb2.Color, + ) + corner_radius: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ImageComponent(proto.Message): + r"""Represents an image. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + image_uri (str): + The image URL. + alt_text (str): + The accessibility label for the image. + crop_style (google.apps.card_v1.types.ImageCropStyle): + The crop style to apply to the image. + border_style (google.apps.card_v1.types.BorderStyle): + The border style to apply to the image. + """ + + image_uri: str = proto.Field( + proto.STRING, + number=1, + ) + alt_text: str = proto.Field( + proto.STRING, + number=2, + ) + crop_style: "ImageCropStyle" = proto.Field( + proto.MESSAGE, + number=3, + message="ImageCropStyle", + ) + border_style: "BorderStyle" = proto.Field( + proto.MESSAGE, + number=4, + message="BorderStyle", + ) + + +class Grid(proto.Message): + r"""Displays a grid with a collection of items. Items can only include + text or images. For responsive columns, or to include more than text + or images, use [``Columns``][google.apps.card.v1.Columns]. For an + example in Google Chat apps, see + `Grid `__. + + A grid supports any number of columns and items. The number of rows + is determined by items divided by columns. A grid with 10 items and + 2 columns has 5 rows. A grid with 11 items and 2 columns has 6 rows. + + `Google Workspace Add-ons and Chat + apps `__: + + For example, the following JSON creates a 2 column grid with a + single item: + + :: + + "grid": { + "title": "A fine collection of items", + "columnCount": 2, + "borderStyle": { + "type": "STROKE", + "cornerRadius": 4 + }, + "items": [ + { + "image": { + "imageUri": "https://www.example.com/image.png", + "cropStyle": { + "type": "SQUARE" + }, + "borderStyle": { + "type": "STROKE" + } + }, + "title": "An item", + "textAlignment": "CENTER" + } + ], + "onClick": { + "openLink": { + "url": "https://www.example.com" + } + } + } + + Attributes: + title (str): + The text that displays in the grid header. + items (MutableSequence[google.apps.card_v1.types.Grid.GridItem]): + The items to display in the grid. + border_style (google.apps.card_v1.types.BorderStyle): + The border style to apply to each grid item. + column_count (int): + The number of columns to display in the grid. + A default value is used if this field isn't + specified, and that default value is different + depending on where the grid is shown (dialog + versus companion). + on_click (google.apps.card_v1.types.OnClick): + This callback is reused by each individual + grid item, but with the item's identifier and + index in the items list added to the callback's + parameters. + """ + + class GridItem(proto.Message): + r"""Represents an item in a grid layout. Items can contain text, an + image, or both text and an image. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + id (str): + A user-specified identifier for this grid item. This + identifier is returned in the parent grid's ``onClick`` + callback parameters. + image (google.apps.card_v1.types.ImageComponent): + The image that displays in the grid item. + title (str): + The grid item's title. + subtitle (str): + The grid item's subtitle. + layout (google.apps.card_v1.types.Grid.GridItem.GridItemLayout): + The layout to use for the grid item. + """ + + class GridItemLayout(proto.Enum): + r"""Represents the various layout options available for a grid item. + + `Google Workspace Add-ons and Chat + apps `__: + + Values: + GRID_ITEM_LAYOUT_UNSPECIFIED (0): + Don't use. Unspecified. + TEXT_BELOW (1): + The title and subtitle are shown below the + grid item's image. + TEXT_ABOVE (2): + The title and subtitle are shown above the + grid item's image. + """ + GRID_ITEM_LAYOUT_UNSPECIFIED = 0 + TEXT_BELOW = 1 + TEXT_ABOVE = 2 + + id: str = proto.Field( + proto.STRING, + number=1, + ) + image: "ImageComponent" = proto.Field( + proto.MESSAGE, + number=2, + message="ImageComponent", + ) + title: str = proto.Field( + proto.STRING, + number=3, + ) + subtitle: str = proto.Field( + proto.STRING, + number=4, + ) + layout: "Grid.GridItem.GridItemLayout" = proto.Field( + proto.ENUM, + number=9, + enum="Grid.GridItem.GridItemLayout", + ) + + title: str = proto.Field( + proto.STRING, + number=1, + ) + items: MutableSequence[GridItem] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=GridItem, + ) + border_style: "BorderStyle" = proto.Field( + proto.MESSAGE, + number=3, + message="BorderStyle", + ) + column_count: int = proto.Field( + proto.INT32, + number=4, + ) + on_click: "OnClick" = proto.Field( + proto.MESSAGE, + number=5, + message="OnClick", + ) + + +class Columns(proto.Message): + r"""The ``Columns`` widget displays up to 2 columns in a card or dialog. + You can add widgets to each column; the widgets appear in the order + that they are specified. For an example in Google Chat apps, see + `Columns `__. + + The height of each column is determined by the taller column. For + example, if the first column is taller than the second column, both + columns have the height of the first column. Because each column can + contain a different number of widgets, you can't define rows or + align widgets between the columns. + + Columns are displayed side-by-side. You can customize the width of + each column using the ``HorizontalSizeStyle`` field. If the user's + screen width is too narrow, the second column wraps below the first: + + - On web, the second column wraps if the screen width is less than + or equal to 480 pixels. + - On iOS devices, the second column wraps if the screen width is + less than or equal to 300 pt. + - On Android devices, the second column wraps if the screen width + is less than or equal to 320 dp. + + To include more than 2 columns, or to use rows, use the + [``Grid``][google.apps.card.v1.Grid] widget. + + `Google Workspace Add-ons and Chat + apps `__: Columns + for Google Workspace Add-ons are in `Developer + Preview `__. + + Attributes: + column_items (MutableSequence[google.apps.card_v1.types.Columns.Column]): + An array of columns. You can include up to 2 + columns in a card or dialog. + """ + + class Column(proto.Message): + r"""A column. + + `Google Chat apps `__: + + Attributes: + horizontal_size_style (google.apps.card_v1.types.Columns.Column.HorizontalSizeStyle): + Specifies how a column fills the width of the card. + + `Google Chat apps `__: + horizontal_alignment (google.apps.card_v1.types.Widget.HorizontalAlignment): + Specifies whether widgets align to the left, + right, or center of a column. + vertical_alignment (google.apps.card_v1.types.Columns.Column.VerticalAlignment): + Specifies whether widgets align to the top, bottom, or + center of a column. + + `Google Chat apps `__: + widgets (MutableSequence[google.apps.card_v1.types.Columns.Column.Widgets]): + An array of widgets included in a column. + Widgets appear in the order that they are + specified. + """ + + class HorizontalSizeStyle(proto.Enum): + r"""Specifies how a column fills the width of the card. The width of + each column depends on both the ``HorizontalSizeStyle`` and the + width of the widgets within the column. + + `Google Chat apps `__: + + Values: + HORIZONTAL_SIZE_STYLE_UNSPECIFIED (0): + Don't use. Unspecified. + FILL_AVAILABLE_SPACE (1): + Default value. Column fills the available space, up to 70% + of the card's width. If both columns are set to + ``FILL_AVAILABLE_SPACE``, each column fills 50% of the + space. + FILL_MINIMUM_SPACE (2): + Column fills the least amount of space + possible and no more than 30% of the card's + width. + """ + HORIZONTAL_SIZE_STYLE_UNSPECIFIED = 0 + FILL_AVAILABLE_SPACE = 1 + FILL_MINIMUM_SPACE = 2 + + class VerticalAlignment(proto.Enum): + r"""Specifies whether widgets align to the top, bottom, or center of a + column. + + `Google Chat apps `__: + + Values: + VERTICAL_ALIGNMENT_UNSPECIFIED (0): + Don't use. Unspecified. + CENTER (1): + Default value. Aligns widgets to the center + of a column. + TOP (2): + Aligns widgets to the top of a column. + BOTTOM (3): + Aligns widgets to the bottom of a column. + """ + VERTICAL_ALIGNMENT_UNSPECIFIED = 0 + CENTER = 1 + TOP = 2 + BOTTOM = 3 + + class Widgets(proto.Message): + r"""The supported widgets that you can include in a column. + + `Google Chat apps `__: + + 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: + text_paragraph (google.apps.card_v1.types.TextParagraph): + [TextParagraph][google.apps.card.v1.TextParagraph] widget. + + This field is a member of `oneof`_ ``data``. + image (google.apps.card_v1.types.Image): + [Image][google.apps.card.v1.Image] widget. + + This field is a member of `oneof`_ ``data``. + decorated_text (google.apps.card_v1.types.DecoratedText): + [DecoratedText][google.apps.card.v1.DecoratedText] widget. + + This field is a member of `oneof`_ ``data``. + button_list (google.apps.card_v1.types.ButtonList): + [ButtonList][google.apps.card.v1.ButtonList] widget. + + This field is a member of `oneof`_ ``data``. + text_input (google.apps.card_v1.types.TextInput): + [TextInput][google.apps.card.v1.TextInput] widget. + + This field is a member of `oneof`_ ``data``. + selection_input (google.apps.card_v1.types.SelectionInput): + [SelectionInput][google.apps.card.v1.SelectionInput] widget. + + This field is a member of `oneof`_ ``data``. + date_time_picker (google.apps.card_v1.types.DateTimePicker): + [DateTimePicker][google.apps.card.v1.DateTimePicker] widget. + + This field is a member of `oneof`_ ``data``. + """ + + text_paragraph: "TextParagraph" = proto.Field( + proto.MESSAGE, + number=1, + oneof="data", + message="TextParagraph", + ) + image: "Image" = proto.Field( + proto.MESSAGE, + number=2, + oneof="data", + message="Image", + ) + decorated_text: "DecoratedText" = proto.Field( + proto.MESSAGE, + number=3, + oneof="data", + message="DecoratedText", + ) + button_list: "ButtonList" = proto.Field( + proto.MESSAGE, + number=4, + oneof="data", + message="ButtonList", + ) + text_input: "TextInput" = proto.Field( + proto.MESSAGE, + number=5, + oneof="data", + message="TextInput", + ) + selection_input: "SelectionInput" = proto.Field( + proto.MESSAGE, + number=6, + oneof="data", + message="SelectionInput", + ) + date_time_picker: "DateTimePicker" = proto.Field( + proto.MESSAGE, + number=7, + oneof="data", + message="DateTimePicker", + ) + + horizontal_size_style: "Columns.Column.HorizontalSizeStyle" = proto.Field( + proto.ENUM, + number=1, + enum="Columns.Column.HorizontalSizeStyle", + ) + horizontal_alignment: "Widget.HorizontalAlignment" = proto.Field( + proto.ENUM, + number=2, + enum="Widget.HorizontalAlignment", + ) + vertical_alignment: "Columns.Column.VerticalAlignment" = proto.Field( + proto.ENUM, + number=3, + enum="Columns.Column.VerticalAlignment", + ) + widgets: MutableSequence["Columns.Column.Widgets"] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="Columns.Column.Widgets", + ) + + column_items: MutableSequence[Column] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Column, + ) + + +class OnClick(proto.Message): + r"""Represents how to respond when users click an interactive element on + a card, such as a button. + + `Google Workspace Add-ons and Chat + apps `__: + + 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: + action (google.apps.card_v1.types.Action): + If specified, an action is triggered by this ``onClick``. + + This field is a member of `oneof`_ ``data``. + open_link (google.apps.card_v1.types.OpenLink): + If specified, this ``onClick`` triggers an open link action. + + This field is a member of `oneof`_ ``data``. + open_dynamic_link_action (google.apps.card_v1.types.Action): + An add-on triggers this action when the action needs to open + a link. This differs from the ``open_link`` above in that + this needs to talk to server to get the link. Thus some + preparation work is required for web client to do before the + open link action response comes back. + + `Google Workspace + Add-ons `__: + + This field is a member of `oneof`_ ``data``. + card (google.apps.card_v1.types.Card): + A new card is pushed to the card stack after clicking if + specified. + + `Google Workspace + Add-ons `__: + + This field is a member of `oneof`_ ``data``. + """ + + action: "Action" = proto.Field( + proto.MESSAGE, + number=1, + oneof="data", + message="Action", + ) + open_link: "OpenLink" = proto.Field( + proto.MESSAGE, + number=2, + oneof="data", + message="OpenLink", + ) + open_dynamic_link_action: "Action" = proto.Field( + proto.MESSAGE, + number=3, + oneof="data", + message="Action", + ) + card: "Card" = proto.Field( + proto.MESSAGE, + number=4, + oneof="data", + message="Card", + ) + + +class OpenLink(proto.Message): + r"""Represents an ``onClick`` event that opens a hyperlink. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + url (str): + The URL to open. + open_as (google.apps.card_v1.types.OpenLink.OpenAs): + How to open a link. + + `Google Workspace + Add-ons `__: + on_close (google.apps.card_v1.types.OpenLink.OnClose): + Whether the client forgets about a link after opening it, or + observes it until the window closes. + + `Google Workspace + Add-ons `__: + """ + + class OpenAs(proto.Enum): + r"""When an ``OnClick`` action opens a link, then the client can either + open it as a full-size window (if that's the frame used by the + client), or an overlay (such as a pop-up). The implementation + depends on the client platform capabilities, and the value selected + might be ignored if the client doesn't support it. ``FULL_SIZE`` is + supported by all clients. + + `Google Workspace + Add-ons `__: + + Values: + FULL_SIZE (0): + The link opens as a full-size window (if + that's the frame used by the client). + OVERLAY (1): + The link opens as an overlay, such as a + pop-up. + """ + FULL_SIZE = 0 + OVERLAY = 1 + + class OnClose(proto.Enum): + r"""What the client does when a link opened by an ``OnClick`` action is + closed. + + Implementation depends on client platform capabilities. For example, + a web browser might open a link in a pop-up window with an + ``OnClose`` handler. + + If both ``OnOpen`` and ``OnClose`` handlers are set, and the client + platform can't support both values, ``OnClose`` takes precedence. + + `Google Workspace + Add-ons `__: + + Values: + NOTHING (0): + Default value. The card doesn't reload; + nothing happens. + RELOAD (1): + Reloads the card after the child window closes. + + If used in conjunction with + ```OpenAs.OVERLAY`` `__, + the child window acts as a modal dialog and the parent card + is blocked until the child window closes. + """ + NOTHING = 0 + RELOAD = 1 + + url: str = proto.Field( + proto.STRING, + number=1, + ) + open_as: OpenAs = proto.Field( + proto.ENUM, + number=2, + enum=OpenAs, + ) + on_close: OnClose = proto.Field( + proto.ENUM, + number=3, + enum=OnClose, + ) + + +class Action(proto.Message): + r"""An action that describes the behavior when the form is submitted. + For example, you can invoke an Apps Script script to handle the + form. If the action is triggered, the form values are sent to the + server. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + function (str): + A custom function to invoke when the containing element is + clicked or othrwise activated. + + For example usage, see `Create interactive + cards `__. + parameters (MutableSequence[google.apps.card_v1.types.Action.ActionParameter]): + List of action parameters. + load_indicator (google.apps.card_v1.types.Action.LoadIndicator): + Specifies the loading indicator that the + action displays while making the call to the + action. + persist_values (bool): + Indicates whether form values persist after the action. The + default value is ``false``. + + If ``true``, form values remain after the action is + triggered. To let the user make changes while the action is + being processed, set + ```LoadIndicator`` `__ + to ``NONE``. For `card + messages `__ + in Chat apps, you must also set the action's + ```ResponseType`` `__ + to ``UPDATE_MESSAGE`` and use the same + ```card_id`` `__ + from the card that contained the action. + + If ``false``, the form values are cleared when the action is + triggered. To prevent the user from making changes while the + action is being processed, set + ```LoadIndicator`` `__ + to ``SPINNER``. + interaction (google.apps.card_v1.types.Action.Interaction): + Optional. Required when opening a + `dialog `__. + + What to do in response to an interaction with a user, such + as a user clicking a button in a card message. + + If unspecified, the app responds by executing an + ``action``—like opening a link or running a function—as + normal. + + By specifying an ``interaction``, the app can respond in + special interactive ways. For example, by setting + ``interaction`` to ``OPEN_DIALOG``, the app can open a + `dialog `__. + When specified, a loading indicator isn't shown. If + specified for an add-on, the entire card is stripped and + nothing is shown in the client. + + `Google Chat apps `__: + """ + + class LoadIndicator(proto.Enum): + r"""Specifies the loading indicator that the action displays while + making the call to the action. + + `Google Workspace Add-ons and Chat + apps `__: + + Values: + SPINNER (0): + Displays a spinner to indicate that content + is loading. + NONE (1): + Nothing is displayed. + """ + SPINNER = 0 + NONE = 1 + + class Interaction(proto.Enum): + r"""Optional. Required when opening a + `dialog `__. + + What to do in response to an interaction with a user, such as a user + clicking a button in a card message. + + If unspecified, the app responds by executing an ``action``—like + opening a link or running a function—as normal. + + By specifying an ``interaction``, the app can respond in special + interactive ways. For example, by setting ``interaction`` to + ``OPEN_DIALOG``, the app can open a + `dialog `__. + + When specified, a loading indicator isn't shown. If specified for an + add-on, the entire card is stripped and nothing is shown in the + client. + + `Google Chat apps `__: + + Values: + INTERACTION_UNSPECIFIED (0): + Default value. The ``action`` executes as normal. + OPEN_DIALOG (1): + Opens a + `dialog `__, + a windowed, card-based interface that Chat apps use to + interact with users. + + Only supported by Chat apps in response to button-clicks on + card messages. If specified for an add-on, the entire card + is stripped and nothing is shown in the client. + + `Google Chat apps `__: + """ + INTERACTION_UNSPECIFIED = 0 + OPEN_DIALOG = 1 + + class ActionParameter(proto.Message): + r"""List of string parameters to supply when the action method is + invoked. For example, consider three snooze buttons: snooze now, + snooze one day, or snooze next week. You might use + ``action method = snooze()``, passing the snooze type and snooze + time in the list of string parameters. + + To learn more, see + ```CommonEventObject`` `__. + + `Google Workspace Add-ons and Chat + apps `__: + + Attributes: + key (str): + The name of the parameter for the action + script. + value (str): + The value of the parameter. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + function: str = proto.Field( + proto.STRING, + number=1, + ) + parameters: MutableSequence[ActionParameter] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=ActionParameter, + ) + load_indicator: LoadIndicator = proto.Field( + proto.ENUM, + number=3, + enum=LoadIndicator, + ) + persist_values: bool = proto.Field( + proto.BOOL, + number=4, + ) + interaction: Interaction = proto.Field( + proto.ENUM, + number=5, + enum=Interaction, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-card/mypy.ini b/packages/google-apps-card/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/packages/google-apps-card/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/packages/google-apps-card/noxfile.py b/packages/google-apps-card/noxfile.py new file mode 100644 index 000000000000..1e6cd48d0529 --- /dev/null +++ b/packages/google-apps-card/noxfile.py @@ -0,0 +1,428 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2023 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 +# +# https://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 by synthtool. DO NOT EDIT! + +from __future__ import absolute_import + +import os +import pathlib +import re +import shutil +from typing import Dict, List +import warnings + +import nox + +BLACK_VERSION = "black[jupyter]==23.7.0" +ISORT_VERSION = "isort==5.11.0" + +LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] + + +DEFAULT_PYTHON_VERSION = "3.10" + +UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "asyncmock", + "pytest", + "pytest-cov", + "pytest-asyncio", +] +UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_DEPENDENCIES: List[str] = [] +UNIT_TEST_EXTRAS: List[str] = [] +UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "pytest", + "google-cloud-testutils", +] +SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_EXTRAS: List[str] = [] +SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +# 'docfx' is excluded since it only needs to run in 'docs-presubmit' +nox.options.sessions = [ + "unit", + "system", + "cover", + "lint", + "lint_setup_py", + "blacken", + "docs", +] + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *LINT_PATHS, + ) + + session.run("flake8", "google", "tests") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def format(session): + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run( + "isort", + "--fss", + *LINT_PATHS, + ) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") + + +def install_unittest_dependencies(session, *constraints): + standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES + session.install(*standard_deps, *constraints) + + if UNIT_TEST_EXTERNAL_DEPENDENCIES: + warnings.warn( + "'unit_test_external_dependencies' is deprecated. Instead, please " + "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", + DeprecationWarning, + ) + session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_LOCAL_DEPENDENCIES: + session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_EXTRAS_BY_PYTHON: + extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif UNIT_TEST_EXTRAS: + extras = UNIT_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +def default(session): + # Install all test dependencies, then install this package in-place. + + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + install_unittest_dependencies(session, "-c", constraints_path) + + # Run py.test against the unit tests. + session.run( + "py.test", + "--quiet", + f"--junitxml=unit_{session.python}_sponge_log.xml", + "--cov=google", + "--cov=tests/unit", + "--cov-append", + "--cov-config=.coveragerc", + "--cov-report=", + "--cov-fail-under=0", + os.path.join("tests", "unit"), + *session.posargs, + ) + + +@nox.session(python=UNIT_TEST_PYTHON_VERSIONS) +def unit(session): + """Run the unit test suite.""" + default(session) + + +def install_systemtest_dependencies(session, *constraints): + # Use pre-release gRPC for system tests. + # Exclude version 1.52.0rc1 which has a known issue. + # See https://github.com/grpc/grpc/issues/32163 + session.install("--pre", "grpcio!=1.52.0rc1") + + session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: + session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_LOCAL_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTRAS_BY_PYTHON: + extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif SYSTEM_TEST_EXTRAS: + extras = SYSTEM_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) +def system(session): + """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + system_test_path = os.path.join("tests", "system.py") + system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") + # Install pyopenssl for mTLS testing. + if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": + session.install("pyopenssl") + + system_test_exists = os.path.exists(system_test_path) + system_test_folder_exists = os.path.exists(system_test_folder_path) + # Sanity check: only run tests if found. + if not system_test_exists and not system_test_folder_exists: + session.skip("System tests were not found") + + install_systemtest_dependencies(session, "-c", constraints_path) + + # Run py.test against the system tests. + if system_test_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_path, + *session.posargs, + ) + if system_test_folder_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_folder_path, + *session.posargs, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "sphinx==4.5.0", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "gcp-sphinx-docfx-yaml", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python="3.12") +def prerelease_deps(session): + """Run all tests with prerelease versions of dependencies installed.""" + + # Install all dependencies + session.install("-e", ".[all, tests, tracing]") + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY + / "testing" + / f"constraints-{UNIT_TEST_PYTHON_VERSIONS[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "protobuf", + # dependency of grpc + "six", + "googleapis-common-protos", + # Exclude version 1.52.0rc1 which has a known issue. See https://github.com/grpc/grpc/issues/32163 + "grpcio!=1.52.0rc1", + "grpcio-status", + "google-api-core", + "google-auth", + "proto-plus", + "google-cloud-testutils", + # dependencies of google-cloud-testutils" + "click", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + + session.run("py.test", "tests/unit") diff --git a/packages/google-apps-card/scripts/decrypt-secrets.sh b/packages/google-apps-card/scripts/decrypt-secrets.sh new file mode 100755 index 000000000000..0018b421ddf8 --- /dev/null +++ b/packages/google-apps-card/scripts/decrypt-secrets.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# Copyright 2023 Google LLC All rights reserved. +# +# 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. + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +ROOT=$( dirname "$DIR" ) + +# Work from the project root. +cd $ROOT + +# Prevent it from overriding files. +# We recommend that sample authors use their own service account files and cloud project. +# In that case, they are supposed to prepare these files by themselves. +if [[ -f "testing/test-env.sh" ]] || \ + [[ -f "testing/service-account.json" ]] || \ + [[ -f "testing/client-secrets.json" ]]; then + echo "One or more target files exist, aborting." + exit 1 +fi + +# Use SECRET_MANAGER_PROJECT if set, fallback to cloud-devrel-kokoro-resources. +PROJECT_ID="${SECRET_MANAGER_PROJECT:-cloud-devrel-kokoro-resources}" + +gcloud secrets versions access latest --secret="python-docs-samples-test-env" \ + --project="${PROJECT_ID}" \ + > testing/test-env.sh +gcloud secrets versions access latest \ + --secret="python-docs-samples-service-account" \ + --project="${PROJECT_ID}" \ + > testing/service-account.json +gcloud secrets versions access latest \ + --secret="python-docs-samples-client-secrets" \ + --project="${PROJECT_ID}" \ + > testing/client-secrets.json diff --git a/packages/google-apps-card/scripts/fixup_card_v1_keywords.py b/packages/google-apps-card/scripts/fixup_card_v1_keywords.py new file mode 100644 index 000000000000..c3a186eb181b --- /dev/null +++ b/packages/google-apps-card/scripts/fixup_card_v1_keywords.py @@ -0,0 +1,175 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class cardCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=cardCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the card client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/packages/google-apps-card/setup.py b/packages/google-apps-card/setup.py new file mode 100644 index 000000000000..f393fc544a2c --- /dev/null +++ b/packages/google-apps-card/setup.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = "google-apps-card" + + +description = "Google Apps Card API client library" + +version = None + +with open(os.path.join(package_root, "google/apps/card/gapic_version.py")) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert len(version_candidates) == 1 + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-card" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/packages/google-apps-card/testing/.gitignore b/packages/google-apps-card/testing/.gitignore new file mode 100644 index 000000000000..b05fbd630881 --- /dev/null +++ b/packages/google-apps-card/testing/.gitignore @@ -0,0 +1,3 @@ +test-env.sh +service-account.json +client-secrets.json \ No newline at end of file diff --git a/packages/google-apps-card/testing/constraints-3.10.txt b/packages/google-apps-card/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-apps-card/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-apps-card/testing/constraints-3.11.txt b/packages/google-apps-card/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-apps-card/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-apps-card/testing/constraints-3.12.txt b/packages/google-apps-card/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-apps-card/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-apps-card/testing/constraints-3.7.txt b/packages/google-apps-card/testing/constraints-3.7.txt new file mode 100644 index 000000000000..b8a550c73855 --- /dev/null +++ b/packages/google-apps-card/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.19.5 diff --git a/packages/google-apps-card/testing/constraints-3.8.txt b/packages/google-apps-card/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-apps-card/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-apps-card/testing/constraints-3.9.txt b/packages/google-apps-card/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-apps-card/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-apps-card/tests/__init__.py b/packages/google-apps-card/tests/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-apps-card/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-apps-card/tests/unit/__init__.py b/packages/google-apps-card/tests/unit/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-apps-card/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-apps-card/tests/unit/gapic/__init__.py b/packages/google-apps-card/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-apps-card/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-apps-card/tests/unit/gapic/card_v1/__init__.py b/packages/google-apps-card/tests/unit/gapic/card_v1/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-apps-card/tests/unit/gapic/card_v1/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-apps-card/tests/unit/gapic/card_v1/test_card.py b/packages/google-apps-card/tests/unit/gapic/card_v1/test_card.py new file mode 100644 index 000000000000..f47dcfa976f4 --- /dev/null +++ b/packages/google-apps-card/tests/unit/gapic/card_v1/test_card.py @@ -0,0 +1,23 @@ +# 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 google.apps import card_v1 + +# NOTE: These are dummy tests to reach 100% coverage +# They simply check that the message can be created. + + +def test_card(): + card_v1.Card() diff --git a/packages/google-apps-chat/.OwlBot.yaml b/packages/google-apps-chat/.OwlBot.yaml new file mode 100644 index 000000000000..9155b2e66e10 --- /dev/null +++ b/packages/google-apps-chat/.OwlBot.yaml @@ -0,0 +1,18 @@ +# Copyright 2022 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. + +deep-copy-regex: + - source: /google/chat/(v.*)/.*-py + dest: /owl-bot-staging/google-apps-chat/$1 +api-name: google-apps-chat diff --git a/packages/google-apps-chat/.coveragerc b/packages/google-apps-chat/.coveragerc new file mode 100644 index 000000000000..94d089777c45 --- /dev/null +++ b/packages/google-apps-chat/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/apps/chat/__init__.py + google/apps/chat/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/packages/google-apps-chat/.flake8 b/packages/google-apps-chat/.flake8 new file mode 100644 index 000000000000..87f6e408c47d --- /dev/null +++ b/packages/google-apps-chat/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2023 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 +# +# https://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 by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E231, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/packages/google-apps-chat/.gitignore b/packages/google-apps-chat/.gitignore new file mode 100644 index 000000000000..b4243ced74e4 --- /dev/null +++ b/packages/google-apps-chat/.gitignore @@ -0,0 +1,63 @@ +*.py[cod] +*.sw[op] + +# C extensions +*.so + +# Packages +*.egg +*.egg-info +dist +build +eggs +.eggs +parts +bin +var +sdist +develop-eggs +.installed.cfg +lib +lib64 +__pycache__ + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.nox +.cache +.pytest_cache + + +# Mac +.DS_Store + +# JetBrains +.idea + +# VS Code +.vscode + +# emacs +*~ + +# Built documentation +docs/_build +bigquery/docs/generated +docs.metadata + +# Virtual environment +env/ + +# Test logs +coverage.xml +*sponge_log.xml + +# System test environment variables. +system_tests/local_test_setup + +# Make sure a generated file isn't accidentally committed. +pylintrc +pylintrc.test diff --git a/packages/google-apps-chat/.repo-metadata.json b/packages/google-apps-chat/.repo-metadata.json new file mode 100644 index 000000000000..8e39314eeb0c --- /dev/null +++ b/packages/google-apps-chat/.repo-metadata.json @@ -0,0 +1,17 @@ +{ + "name": "google-apps-chat", + "name_pretty": "Chat API", + "api_description": "", + "product_documentation": "https://developers.google.com/chat/", + "client_documentation": "https://googleapis.dev/python/google-apps-chat/latest", + "issue_tracker": "https://github.com/googleapis/google-cloud-python/issues", + "release_level": "preview", + "language": "python", + "library_type": "GAPIC_AUTO", + "repo": "googleapis/google-cloud-python", + "distribution_name": "google-apps-chat", + "api_id": "chat.googleapis.com", + "default_version": "v1", + "codeowner_team": "", + "api_shortname": "chat" +} diff --git a/packages/google-apps-chat/CHANGELOG.md b/packages/google-apps-chat/CHANGELOG.md new file mode 100644 index 000000000000..fa40325803d5 --- /dev/null +++ b/packages/google-apps-chat/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +## 0.1.0 (2024-03-05) + + +### Features + +* add initial files for google.apps.chat.v1 ([#12379](https://github.com/googleapis/google-cloud-python/issues/12379)) ([cd56a46](https://github.com/googleapis/google-cloud-python/commit/cd56a4683d04eff015e23ee5fc9a319cfc1f3405)) + +## Changelog diff --git a/packages/google-apps-chat/CODE_OF_CONDUCT.md b/packages/google-apps-chat/CODE_OF_CONDUCT.md new file mode 100644 index 000000000000..039f43681204 --- /dev/null +++ b/packages/google-apps-chat/CODE_OF_CONDUCT.md @@ -0,0 +1,95 @@ + +# Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of +experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, or to ban temporarily or permanently any +contributor for other behaviors that they deem inappropriate, threatening, +offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +This Code of Conduct also applies outside the project spaces when the Project +Steward has a reasonable belief that an individual's behavior may have a +negative impact on the project or its community. + +## Conflict Resolution + +We do not believe that all conflict is bad; healthy debate and disagreement +often yield positive results. However, it is never okay to be disrespectful or +to engage in behavior that violates the project’s code of conduct. + +If you see someone violating the code of conduct, you are encouraged to address +the behavior directly with those involved. Many issues can be resolved quickly +and easily, and this gives people more control over the outcome of their +dispute. If you are unable to resolve the matter for any reason, or if the +behavior is threatening or harassing, report it. We are dedicated to providing +an environment where participants feel welcome and safe. + + +Reports should be directed to *googleapis-stewards@google.com*, the +Project Steward(s) for *Google Cloud Client Libraries*. It is the Project Steward’s duty to +receive and address reported violations of the code of conduct. They will then +work with a committee consisting of representatives from the Open Source +Programs Office and the Google Open Source Strategy team. If for any reason you +are uncomfortable reaching out to the Project Steward, please email +opensource@google.com. + +We will investigate every complaint, but you may not receive a direct response. +We will use our discretion in determining when and how to follow up on reported +incidents, which may range from not taking action to permanent expulsion from +the project and project-sponsored spaces. We will notify the accused of the +report and provide them an opportunity to discuss it before any action is taken. +The identity of the reporter will be omitted from the details of the report +supplied to the accused. In potentially harmful situations, such as ongoing +harassment or threats to anyone's safety, we may take action without notice. + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 1.4, +available at +https://www.contributor-covenant.org/version/1/4/code-of-conduct.html \ No newline at end of file diff --git a/packages/google-apps-chat/CONTRIBUTING.rst b/packages/google-apps-chat/CONTRIBUTING.rst new file mode 100644 index 000000000000..0b7187fafcf0 --- /dev/null +++ b/packages/google-apps-chat/CONTRIBUTING.rst @@ -0,0 +1,271 @@ +.. Generated by synthtool. DO NOT EDIT! +############ +Contributing +############ + +#. **Please sign one of the contributor license agreements below.** +#. Fork the repo, develop and test your code changes, add docs. +#. Make sure that your commit messages clearly describe the changes. +#. Send a pull request. (Please Read: `Faster Pull Request Reviews`_) + +.. _Faster Pull Request Reviews: https://github.com/kubernetes/community/blob/master/contributors/guide/pull-requests.md#best-practices-for-faster-reviews + +.. contents:: Here are some guidelines for hacking on the Google Cloud Client libraries. + +*************** +Adding Features +*************** + +In order to add a feature: + +- The feature must be documented in both the API and narrative + documentation. + +- The feature must work fully on the following CPython versions: + 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + +- The feature must not add unnecessary dependencies (where + "unnecessary" is of course subjective, but new dependencies should + be discussed). + +**************************** +Using a Development Checkout +**************************** + +You'll have to create a development environment using a Git checkout: + +- While logged into your GitHub account, navigate to the + ``google-cloud-python`` `repo`_ on GitHub. + +- Fork and clone the ``google-cloud-python`` repository to your GitHub account by + clicking the "Fork" button. + +- Clone your fork of ``google-cloud-python`` from your GitHub account to your local + computer, substituting your account username and specifying the destination + as ``hack-on-google-cloud-python``. E.g.:: + + $ cd ${HOME} + $ git clone git@github.com:USERNAME/google-cloud-python.git hack-on-google-cloud-python + $ cd hack-on-google-cloud-python + # Configure remotes such that you can pull changes from the googleapis/google-cloud-python + # repository into your local repository. + $ git remote add upstream git@github.com:googleapis/google-cloud-python.git + # fetch and merge changes from upstream into main + $ git fetch upstream + $ git merge upstream/main + +Now your local repo is set up such that you will push changes to your GitHub +repo, from which you can submit a pull request. + +To work on the codebase and run the tests, we recommend using ``nox``, +but you can also use a ``virtualenv`` of your own creation. + +.. _repo: https://github.com/googleapis/google-cloud-python + +Using ``nox`` +============= + +We use `nox `__ to instrument our tests. + +- To test your changes, run unit tests with ``nox``:: + $ nox -s unit + +- To run a single unit test:: + + $ nox -s unit-3.12 -- -k + + + .. note:: + + The unit tests and system tests are described in the + ``noxfile.py`` files in each directory. + +.. nox: https://pypi.org/project/nox/ + +***************************************** +I'm getting weird errors... Can you help? +***************************************** + +If the error mentions ``Python.h`` not being found, +install ``python-dev`` and try again. +On Debian/Ubuntu:: + + $ sudo apt-get install python-dev + +************ +Coding Style +************ +- We use the automatic code formatter ``black``. You can run it using + the nox session ``blacken``. This will eliminate many lint errors. Run via:: + + $ nox -s blacken + +- PEP8 compliance is required, with exceptions defined in the linter configuration. + If you have ``nox`` installed, you can test that you have not introduced + any non-compliant code via:: + + $ nox -s lint + +- In order to make ``nox -s lint`` run faster, you can set some environment + variables:: + + export GOOGLE_CLOUD_TESTING_REMOTE="upstream" + export GOOGLE_CLOUD_TESTING_BRANCH="main" + + By doing this, you are specifying the location of the most up-to-date + version of ``google-cloud-python``. The + remote name ``upstream`` should point to the official ``googleapis`` + checkout and the branch should be the default branch on that remote (``main``). + +- This repository contains configuration for the + `pre-commit `__ tool, which automates checking + our linters during a commit. If you have it installed on your ``$PATH``, + you can enable enforcing those checks via: + +.. code-block:: bash + + $ pre-commit install + pre-commit installed at .git/hooks/pre-commit + +Exceptions to PEP8: + +- Many unit tests use a helper method, ``_call_fut`` ("FUT" is short for + "Function-Under-Test"), which is PEP8-incompliant, but more readable. + Some also use a local variable, ``MUT`` (short for "Module-Under-Test"). + +******************** +Running System Tests +******************** + +- To run system tests, you can execute:: + + # Run all system tests + $ nox -s system + + # Run a single system test + $ nox -s system-3.12 -- -k + + + .. note:: + + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + For expediency, we do not run them in older versions of Python 3. + + This alone will not run the tests. You'll need to change some local + auth settings and change some configuration in your project to + run all the tests. + +- System tests will be run against an actual project. You should use local credentials from gcloud when possible. See `Best practices for application authentication `__. Some tests require a service account. For those tests see `Authenticating as a service account `__. + +************* +Test Coverage +************* + +- The codebase *must* have 100% test statement coverage after each commit. + You can test coverage via ``nox -s cover``. + +****************************************************** +Documentation Coverage and Building HTML Documentation +****************************************************** + +If you fix a bug, and the bug requires an API or behavior modification, all +documentation in this package which references that API or behavior must be +changed to reflect the bug fix, ideally in the same commit that fixes the bug +or adds the feature. + +Build the docs via: + + $ nox -s docs + +************************* +Samples and code snippets +************************* + +Code samples and snippets live in the `samples/` catalogue. Feel free to +provide more examples, but make sure to write tests for those examples. +Each folder containing example code requires its own `noxfile.py` script +which automates testing. If you decide to create a new folder, you can +base it on the `samples/snippets` folder (providing `noxfile.py` and +the requirements files). + +The tests will run against a real Google Cloud Project, so you should +configure them just like the System Tests. + +- To run sample tests, you can execute:: + + # Run all tests in a folder + $ cd samples/snippets + $ nox -s py-3.8 + + # Run a single sample test + $ cd samples/snippets + $ nox -s py-3.8 -- -k + +******************************************** +Note About ``README`` as it pertains to PyPI +******************************************** + +The `description on PyPI`_ for the project comes directly from the +``README``. Due to the reStructuredText (``rst``) parser used by +PyPI, relative links which will work on GitHub (e.g. ``CONTRIBUTING.rst`` +instead of +``https://github.com/googleapis/google-cloud-python/blob/main/CONTRIBUTING.rst``) +may cause problems creating links or rendering the description. + +.. _description on PyPI: https://pypi.org/project/google-apps-chat + + +************************* +Supported Python Versions +************************* + +We support: + +- `Python 3.7`_ +- `Python 3.8`_ +- `Python 3.9`_ +- `Python 3.10`_ +- `Python 3.11`_ +- `Python 3.12`_ + +.. _Python 3.7: https://docs.python.org/3.7/ +.. _Python 3.8: https://docs.python.org/3.8/ +.. _Python 3.9: https://docs.python.org/3.9/ +.. _Python 3.10: https://docs.python.org/3.10/ +.. _Python 3.11: https://docs.python.org/3.11/ +.. _Python 3.12: https://docs.python.org/3.12/ + + +Supported versions can be found in our ``noxfile.py`` `config`_. + +.. _config: https://github.com/googleapis/google-cloud-python/blob/main/packages/google-apps-chat/noxfile.py + + +********** +Versioning +********** + +This library follows `Semantic Versioning`_. + +.. _Semantic Versioning: http://semver.org/ + +Some packages are currently in major version zero (``0.y.z``), which means that +anything may change at any time and the public API should not be considered +stable. + +****************************** +Contributor License Agreements +****************************** + +Before we can accept your pull requests you'll need to sign a Contributor +License Agreement (CLA): + +- **If you are an individual writing original source code** and **you own the + intellectual property**, then you'll need to sign an + `individual CLA `__. +- **If you work for a company that wants to allow you to contribute your work**, + then you'll need to sign a + `corporate CLA `__. + +You can sign these electronically (just scroll to the bottom). After that, +we'll be able to accept your pull requests. diff --git a/packages/google-apps-chat/LICENSE b/packages/google-apps-chat/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/packages/google-apps-chat/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/packages/google-apps-chat/MANIFEST.in b/packages/google-apps-chat/MANIFEST.in new file mode 100644 index 000000000000..e0a66705318e --- /dev/null +++ b/packages/google-apps-chat/MANIFEST.in @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2023 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 +# +# https://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 by synthtool. DO NOT EDIT! +include README.rst LICENSE +recursive-include google *.json *.proto py.typed +recursive-include tests * +global-exclude *.py[co] +global-exclude __pycache__ + +# Exclude scripts for samples readmegen +prune scripts/readme-gen diff --git a/packages/google-apps-chat/README.rst b/packages/google-apps-chat/README.rst new file mode 100644 index 000000000000..6cd1ba088336 --- /dev/null +++ b/packages/google-apps-chat/README.rst @@ -0,0 +1,108 @@ +Python Client for Chat API +========================== + +|preview| |pypi| |versions| + +`Chat API`_: + +- `Client Library Documentation`_ +- `Product Documentation`_ + +.. |preview| image:: https://img.shields.io/badge/support-preview-orange.svg + :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#stability-levels +.. |pypi| image:: https://img.shields.io/pypi/v/google-apps-chat.svg + :target: https://pypi.org/project/google-apps-chat/ +.. |versions| image:: https://img.shields.io/pypi/pyversions/google-apps-chat.svg + :target: https://pypi.org/project/google-apps-chat/ +.. _Chat API: https://developers.google.com/chat/ +.. _Client Library Documentation: https://googleapis.dev/python/google-apps-chat/latest +.. _Product Documentation: https://developers.google.com/chat/ + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. `Enable the Chat API.`_ +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Enable the Chat API.: https://developers.google.com/chat/ +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a virtual environment using `venv`_. `venv`_ is a tool that +creates isolated Python environments. These isolated environments can have separate +versions of Python packages, which allows you to isolate one project's dependencies +from the dependencies of other projects. + +With `venv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`venv`: https://docs.python.org/3/library/venv.html + + +Code samples and snippets +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Code samples and snippets live in the `samples/`_ folder. + +.. _samples/: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-chat/samples + + +Supported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^ +Our client libraries are compatible with all current `active`_ and `maintenance`_ versions of +Python. + +Python >= 3.7 + +.. _active: https://devguide.python.org/devcycle/#in-development-main-branch +.. _maintenance: https://devguide.python.org/devcycle/#maintenance-branches + +Unsupported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Python <= 3.6 + +If you are using an `end-of-life`_ +version of Python, we recommend that you update as soon as possible to an actively supported version. + +.. _end-of-life: https://devguide.python.org/devcycle/#end-of-life-branches + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + pip install google-apps-chat + + +Windows +^^^^^^^ + +.. code-block:: console + + py -m venv + .\\Scripts\activate + pip install google-apps-chat + +Next Steps +~~~~~~~~~~ + +- Read the `Client Library Documentation`_ for Chat API + to see other available methods on the client. +- Read the `Chat API Product documentation`_ to learn + more about the product and see How-to Guides. +- View this `README`_ to see the full list of Cloud + APIs that we cover. + +.. _Chat API Product documentation: https://developers.google.com/chat/ +.. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst diff --git a/packages/google-apps-chat/chat-v1-py.tar.gz b/packages/google-apps-chat/chat-v1-py.tar.gz new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/packages/google-apps-chat/docs/CHANGELOG.md b/packages/google-apps-chat/docs/CHANGELOG.md new file mode 120000 index 000000000000..04c99a55caae --- /dev/null +++ b/packages/google-apps-chat/docs/CHANGELOG.md @@ -0,0 +1 @@ +../CHANGELOG.md \ No newline at end of file diff --git a/packages/google-apps-chat/docs/README.rst b/packages/google-apps-chat/docs/README.rst new file mode 120000 index 000000000000..89a0106941ff --- /dev/null +++ b/packages/google-apps-chat/docs/README.rst @@ -0,0 +1 @@ +../README.rst \ No newline at end of file diff --git a/packages/google-apps-chat/docs/_static/custom.css b/packages/google-apps-chat/docs/_static/custom.css new file mode 100644 index 000000000000..b0a295464b23 --- /dev/null +++ b/packages/google-apps-chat/docs/_static/custom.css @@ -0,0 +1,20 @@ +div#python2-eol { + border-color: red; + border-width: medium; +} + +/* Ensure minimum width for 'Parameters' / 'Returns' column */ +dl.field-list > dt { + min-width: 100px +} + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/packages/google-apps-chat/docs/_templates/layout.html b/packages/google-apps-chat/docs/_templates/layout.html new file mode 100644 index 000000000000..6316a537f72b --- /dev/null +++ b/packages/google-apps-chat/docs/_templates/layout.html @@ -0,0 +1,50 @@ + +{% extends "!layout.html" %} +{%- block content %} +{%- if theme_fixed_sidebar|lower == 'true' %} +
+ {{ sidebar() }} + {%- block document %} +
+ {%- if render_sidebar %} +
+ {%- endif %} + + {%- block relbar_top %} + {%- if theme_show_relbar_top|tobool %} + + {%- endif %} + {% endblock %} + +
+
+ As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please + visit Python 2 support on Google Cloud. +
+ {% block body %} {% endblock %} +
+ + {%- block relbar_bottom %} + {%- if theme_show_relbar_bottom|tobool %} + + {%- endif %} + {% endblock %} + + {%- if render_sidebar %} +
+ {%- endif %} +
+ {%- endblock %} +
+
+{%- else %} +{{ super() }} +{%- endif %} +{%- endblock %} diff --git a/packages/google-apps-chat/docs/chat_v1/chat_service.rst b/packages/google-apps-chat/docs/chat_v1/chat_service.rst new file mode 100644 index 000000000000..2fc1f0f335d2 --- /dev/null +++ b/packages/google-apps-chat/docs/chat_v1/chat_service.rst @@ -0,0 +1,10 @@ +ChatService +----------------------------- + +.. automodule:: google.apps.chat_v1.services.chat_service + :members: + :inherited-members: + +.. automodule:: google.apps.chat_v1.services.chat_service.pagers + :members: + :inherited-members: diff --git a/packages/google-apps-chat/docs/chat_v1/services_.rst b/packages/google-apps-chat/docs/chat_v1/services_.rst new file mode 100644 index 000000000000..e59fdb30cdd4 --- /dev/null +++ b/packages/google-apps-chat/docs/chat_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Apps Chat v1 API +==================================== +.. toctree:: + :maxdepth: 2 + + chat_service diff --git a/packages/google-apps-chat/docs/chat_v1/types_.rst b/packages/google-apps-chat/docs/chat_v1/types_.rst new file mode 100644 index 000000000000..e786c9b1231a --- /dev/null +++ b/packages/google-apps-chat/docs/chat_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Apps Chat v1 API +================================= + +.. automodule:: google.apps.chat_v1.types + :members: + :show-inheritance: diff --git a/packages/google-apps-chat/docs/conf.py b/packages/google-apps-chat/docs/conf.py new file mode 100644 index 000000000000..8182e7c001b1 --- /dev/null +++ b/packages/google-apps-chat/docs/conf.py @@ -0,0 +1,384 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# +# google-apps-chat documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import os +import shlex +import sys + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + +__version__ = "" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.5.5" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.doctest", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", + "recommonmark", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_options = {"members": True} +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = "google-apps-chat" +copyright = "2019, Google" +author = "Google APIs" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [ + "_build", + "**/.nox/**/*", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for google-apps-chat", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-apps-chat-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + #'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + #'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + #'preamble': '', + # Latex figure (float) alignment + #'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-apps-chat.tex", + "google-apps-chat Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-apps-chat", + "google-apps-chat Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-apps-chat", + "google-apps-chat Documentation", + author, + "google-apps-chat", + "google-apps-chat Library", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), + "google.api_core": ( + "https://googleapis.dev/python/google-api-core/latest/", + None, + ), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/packages/google-apps-chat/docs/index.rst b/packages/google-apps-chat/docs/index.rst new file mode 100644 index 000000000000..8493308daba0 --- /dev/null +++ b/packages/google-apps-chat/docs/index.rst @@ -0,0 +1,23 @@ +.. include:: README.rst + +.. include:: multiprocessing.rst + + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + chat_v1/services_ + chat_v1/types_ + + +Changelog +--------- + +For a list of all ``google-apps-chat`` releases: + +.. toctree:: + :maxdepth: 2 + + CHANGELOG diff --git a/packages/google-apps-chat/docs/multiprocessing.rst b/packages/google-apps-chat/docs/multiprocessing.rst new file mode 100644 index 000000000000..536d17b2ea65 --- /dev/null +++ b/packages/google-apps-chat/docs/multiprocessing.rst @@ -0,0 +1,7 @@ +.. note:: + + Because this client uses :mod:`grpc` library, it is safe to + share instances across threads. In multiprocessing scenarios, the best + practice is to create client instances *after* the invocation of + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or + :class:`multiprocessing.Process`. diff --git a/packages/google-apps-chat/google/apps/chat/__init__.py b/packages/google-apps-chat/google/apps/chat/__init__.py new file mode 100644 index 000000000000..352dfedeabad --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat/__init__.py @@ -0,0 +1,157 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 google.apps.chat import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.apps.chat_v1.services.chat_service.async_client import ( + ChatServiceAsyncClient, +) +from google.apps.chat_v1.services.chat_service.client import ChatServiceClient +from google.apps.chat_v1.types.action_status import ActionStatus +from google.apps.chat_v1.types.annotation import ( + Annotation, + AnnotationType, + SlashCommandMetadata, + UserMentionMetadata, +) +from google.apps.chat_v1.types.attachment import ( + Attachment, + AttachmentDataRef, + DriveDataRef, + GetAttachmentRequest, + UploadAttachmentRequest, + UploadAttachmentResponse, +) +from google.apps.chat_v1.types.contextual_addon import ContextualAddOnMarkup +from google.apps.chat_v1.types.deletion_metadata import DeletionMetadata +from google.apps.chat_v1.types.group import Group +from google.apps.chat_v1.types.history_state import HistoryState +from google.apps.chat_v1.types.matched_url import MatchedUrl +from google.apps.chat_v1.types.membership import ( + CreateMembershipRequest, + DeleteMembershipRequest, + GetMembershipRequest, + ListMembershipsRequest, + ListMembershipsResponse, + Membership, +) +from google.apps.chat_v1.types.message import ( + ActionResponse, + AttachedGif, + CardWithId, + CreateMessageRequest, + DeleteMessageRequest, + Dialog, + DialogAction, + GetMessageRequest, + ListMessagesRequest, + ListMessagesResponse, + Message, + QuotedMessageMetadata, + Thread, + UpdateMessageRequest, +) +from google.apps.chat_v1.types.reaction import ( + CreateReactionRequest, + CustomEmoji, + DeleteReactionRequest, + Emoji, + EmojiReactionSummary, + ListReactionsRequest, + ListReactionsResponse, + Reaction, +) +from google.apps.chat_v1.types.slash_command import SlashCommand +from google.apps.chat_v1.types.space import ( + CompleteImportSpaceRequest, + CompleteImportSpaceResponse, + CreateSpaceRequest, + DeleteSpaceRequest, + FindDirectMessageRequest, + GetSpaceRequest, + ListSpacesRequest, + ListSpacesResponse, + Space, + UpdateSpaceRequest, +) +from google.apps.chat_v1.types.space_setup import SetUpSpaceRequest +from google.apps.chat_v1.types.user import User +from google.apps.chat_v1.types.widgets import WidgetMarkup + +__all__ = ( + "ChatServiceClient", + "ChatServiceAsyncClient", + "ActionStatus", + "Annotation", + "SlashCommandMetadata", + "UserMentionMetadata", + "AnnotationType", + "Attachment", + "AttachmentDataRef", + "DriveDataRef", + "GetAttachmentRequest", + "UploadAttachmentRequest", + "UploadAttachmentResponse", + "ContextualAddOnMarkup", + "DeletionMetadata", + "Group", + "HistoryState", + "MatchedUrl", + "CreateMembershipRequest", + "DeleteMembershipRequest", + "GetMembershipRequest", + "ListMembershipsRequest", + "ListMembershipsResponse", + "Membership", + "ActionResponse", + "AttachedGif", + "CardWithId", + "CreateMessageRequest", + "DeleteMessageRequest", + "Dialog", + "DialogAction", + "GetMessageRequest", + "ListMessagesRequest", + "ListMessagesResponse", + "Message", + "QuotedMessageMetadata", + "Thread", + "UpdateMessageRequest", + "CreateReactionRequest", + "CustomEmoji", + "DeleteReactionRequest", + "Emoji", + "EmojiReactionSummary", + "ListReactionsRequest", + "ListReactionsResponse", + "Reaction", + "SlashCommand", + "CompleteImportSpaceRequest", + "CompleteImportSpaceResponse", + "CreateSpaceRequest", + "DeleteSpaceRequest", + "FindDirectMessageRequest", + "GetSpaceRequest", + "ListSpacesRequest", + "ListSpacesResponse", + "Space", + "UpdateSpaceRequest", + "SetUpSpaceRequest", + "User", + "WidgetMarkup", +) diff --git a/packages/google-apps-chat/google/apps/chat/gapic_version.py b/packages/google-apps-chat/google/apps/chat/gapic_version.py new file mode 100644 index 000000000000..a7d39deb7a45 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/packages/google-apps-chat/google/apps/chat/py.typed b/packages/google-apps-chat/google/apps/chat/py.typed new file mode 100644 index 000000000000..dcdf2700193b --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-apps-chat package uses inline types. diff --git a/packages/google-apps-chat/google/apps/chat_v1/__init__.py b/packages/google-apps-chat/google/apps/chat_v1/__init__.py new file mode 100644 index 000000000000..6498fda7adb9 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/__init__.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 google.apps.chat_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.chat_service import ChatServiceAsyncClient, ChatServiceClient +from .types.action_status import ActionStatus +from .types.annotation import ( + Annotation, + AnnotationType, + SlashCommandMetadata, + UserMentionMetadata, +) +from .types.attachment import ( + Attachment, + AttachmentDataRef, + DriveDataRef, + GetAttachmentRequest, + UploadAttachmentRequest, + UploadAttachmentResponse, +) +from .types.contextual_addon import ContextualAddOnMarkup +from .types.deletion_metadata import DeletionMetadata +from .types.group import Group +from .types.history_state import HistoryState +from .types.matched_url import MatchedUrl +from .types.membership import ( + CreateMembershipRequest, + DeleteMembershipRequest, + GetMembershipRequest, + ListMembershipsRequest, + ListMembershipsResponse, + Membership, +) +from .types.message import ( + ActionResponse, + AttachedGif, + CardWithId, + CreateMessageRequest, + DeleteMessageRequest, + Dialog, + DialogAction, + GetMessageRequest, + ListMessagesRequest, + ListMessagesResponse, + Message, + QuotedMessageMetadata, + Thread, + UpdateMessageRequest, +) +from .types.reaction import ( + CreateReactionRequest, + CustomEmoji, + DeleteReactionRequest, + Emoji, + EmojiReactionSummary, + ListReactionsRequest, + ListReactionsResponse, + Reaction, +) +from .types.slash_command import SlashCommand +from .types.space import ( + CompleteImportSpaceRequest, + CompleteImportSpaceResponse, + CreateSpaceRequest, + DeleteSpaceRequest, + FindDirectMessageRequest, + GetSpaceRequest, + ListSpacesRequest, + ListSpacesResponse, + Space, + UpdateSpaceRequest, +) +from .types.space_setup import SetUpSpaceRequest +from .types.user import User +from .types.widgets import WidgetMarkup + +__all__ = ( + "ChatServiceAsyncClient", + "ActionResponse", + "ActionStatus", + "Annotation", + "AnnotationType", + "AttachedGif", + "Attachment", + "AttachmentDataRef", + "CardWithId", + "ChatServiceClient", + "CompleteImportSpaceRequest", + "CompleteImportSpaceResponse", + "ContextualAddOnMarkup", + "CreateMembershipRequest", + "CreateMessageRequest", + "CreateReactionRequest", + "CreateSpaceRequest", + "CustomEmoji", + "DeleteMembershipRequest", + "DeleteMessageRequest", + "DeleteReactionRequest", + "DeleteSpaceRequest", + "DeletionMetadata", + "Dialog", + "DialogAction", + "DriveDataRef", + "Emoji", + "EmojiReactionSummary", + "FindDirectMessageRequest", + "GetAttachmentRequest", + "GetMembershipRequest", + "GetMessageRequest", + "GetSpaceRequest", + "Group", + "HistoryState", + "ListMembershipsRequest", + "ListMembershipsResponse", + "ListMessagesRequest", + "ListMessagesResponse", + "ListReactionsRequest", + "ListReactionsResponse", + "ListSpacesRequest", + "ListSpacesResponse", + "MatchedUrl", + "Membership", + "Message", + "QuotedMessageMetadata", + "Reaction", + "SetUpSpaceRequest", + "SlashCommand", + "SlashCommandMetadata", + "Space", + "Thread", + "UpdateMessageRequest", + "UpdateSpaceRequest", + "UploadAttachmentRequest", + "UploadAttachmentResponse", + "User", + "UserMentionMetadata", + "WidgetMarkup", +) diff --git a/packages/google-apps-chat/google/apps/chat_v1/gapic_metadata.json b/packages/google-apps-chat/google/apps/chat_v1/gapic_metadata.json new file mode 100644 index 000000000000..5c89a784ee6f --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/gapic_metadata.json @@ -0,0 +1,358 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.apps.chat_v1", + "protoPackage": "google.chat.v1", + "schema": "1.0", + "services": { + "ChatService": { + "clients": { + "grpc": { + "libraryClient": "ChatServiceClient", + "rpcs": { + "CompleteImportSpace": { + "methods": [ + "complete_import_space" + ] + }, + "CreateMembership": { + "methods": [ + "create_membership" + ] + }, + "CreateMessage": { + "methods": [ + "create_message" + ] + }, + "CreateReaction": { + "methods": [ + "create_reaction" + ] + }, + "CreateSpace": { + "methods": [ + "create_space" + ] + }, + "DeleteMembership": { + "methods": [ + "delete_membership" + ] + }, + "DeleteMessage": { + "methods": [ + "delete_message" + ] + }, + "DeleteReaction": { + "methods": [ + "delete_reaction" + ] + }, + "DeleteSpace": { + "methods": [ + "delete_space" + ] + }, + "FindDirectMessage": { + "methods": [ + "find_direct_message" + ] + }, + "GetAttachment": { + "methods": [ + "get_attachment" + ] + }, + "GetMembership": { + "methods": [ + "get_membership" + ] + }, + "GetMessage": { + "methods": [ + "get_message" + ] + }, + "GetSpace": { + "methods": [ + "get_space" + ] + }, + "ListMemberships": { + "methods": [ + "list_memberships" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + }, + "ListReactions": { + "methods": [ + "list_reactions" + ] + }, + "ListSpaces": { + "methods": [ + "list_spaces" + ] + }, + "SetUpSpace": { + "methods": [ + "set_up_space" + ] + }, + "UpdateMessage": { + "methods": [ + "update_message" + ] + }, + "UpdateSpace": { + "methods": [ + "update_space" + ] + }, + "UploadAttachment": { + "methods": [ + "upload_attachment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ChatServiceAsyncClient", + "rpcs": { + "CompleteImportSpace": { + "methods": [ + "complete_import_space" + ] + }, + "CreateMembership": { + "methods": [ + "create_membership" + ] + }, + "CreateMessage": { + "methods": [ + "create_message" + ] + }, + "CreateReaction": { + "methods": [ + "create_reaction" + ] + }, + "CreateSpace": { + "methods": [ + "create_space" + ] + }, + "DeleteMembership": { + "methods": [ + "delete_membership" + ] + }, + "DeleteMessage": { + "methods": [ + "delete_message" + ] + }, + "DeleteReaction": { + "methods": [ + "delete_reaction" + ] + }, + "DeleteSpace": { + "methods": [ + "delete_space" + ] + }, + "FindDirectMessage": { + "methods": [ + "find_direct_message" + ] + }, + "GetAttachment": { + "methods": [ + "get_attachment" + ] + }, + "GetMembership": { + "methods": [ + "get_membership" + ] + }, + "GetMessage": { + "methods": [ + "get_message" + ] + }, + "GetSpace": { + "methods": [ + "get_space" + ] + }, + "ListMemberships": { + "methods": [ + "list_memberships" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + }, + "ListReactions": { + "methods": [ + "list_reactions" + ] + }, + "ListSpaces": { + "methods": [ + "list_spaces" + ] + }, + "SetUpSpace": { + "methods": [ + "set_up_space" + ] + }, + "UpdateMessage": { + "methods": [ + "update_message" + ] + }, + "UpdateSpace": { + "methods": [ + "update_space" + ] + }, + "UploadAttachment": { + "methods": [ + "upload_attachment" + ] + } + } + }, + "rest": { + "libraryClient": "ChatServiceClient", + "rpcs": { + "CompleteImportSpace": { + "methods": [ + "complete_import_space" + ] + }, + "CreateMembership": { + "methods": [ + "create_membership" + ] + }, + "CreateMessage": { + "methods": [ + "create_message" + ] + }, + "CreateReaction": { + "methods": [ + "create_reaction" + ] + }, + "CreateSpace": { + "methods": [ + "create_space" + ] + }, + "DeleteMembership": { + "methods": [ + "delete_membership" + ] + }, + "DeleteMessage": { + "methods": [ + "delete_message" + ] + }, + "DeleteReaction": { + "methods": [ + "delete_reaction" + ] + }, + "DeleteSpace": { + "methods": [ + "delete_space" + ] + }, + "FindDirectMessage": { + "methods": [ + "find_direct_message" + ] + }, + "GetAttachment": { + "methods": [ + "get_attachment" + ] + }, + "GetMembership": { + "methods": [ + "get_membership" + ] + }, + "GetMessage": { + "methods": [ + "get_message" + ] + }, + "GetSpace": { + "methods": [ + "get_space" + ] + }, + "ListMemberships": { + "methods": [ + "list_memberships" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + }, + "ListReactions": { + "methods": [ + "list_reactions" + ] + }, + "ListSpaces": { + "methods": [ + "list_spaces" + ] + }, + "SetUpSpace": { + "methods": [ + "set_up_space" + ] + }, + "UpdateMessage": { + "methods": [ + "update_message" + ] + }, + "UpdateSpace": { + "methods": [ + "update_space" + ] + }, + "UploadAttachment": { + "methods": [ + "upload_attachment" + ] + } + } + } + } + } + } +} 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 new file mode 100644 index 000000000000..a7d39deb7a45 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/packages/google-apps-chat/google/apps/chat_v1/py.typed b/packages/google-apps-chat/google/apps/chat_v1/py.typed new file mode 100644 index 000000000000..dcdf2700193b --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-apps-chat package uses inline types. diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/__init__.py b/packages/google-apps-chat/google/apps/chat_v1/services/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/__init__.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/__init__.py new file mode 100644 index 000000000000..56283bd7834c --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .async_client import ChatServiceAsyncClient +from .client import ChatServiceClient + +__all__ = ( + "ChatServiceClient", + "ChatServiceAsyncClient", +) diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/async_client.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/async_client.py new file mode 100644 index 000000000000..a28d6068564c --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/async_client.py @@ -0,0 +1,3131 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.apps.chat_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.apps.chat_v1.services.chat_service import pagers +from google.apps.chat_v1.types import ( + annotation, + attachment, + contextual_addon, + deletion_metadata, + group, + history_state, + matched_url, +) +from google.apps.chat_v1.types import membership +from google.apps.chat_v1.types import membership as gc_membership +from google.apps.chat_v1.types import message +from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import slash_command +from google.apps.chat_v1.types import space +from google.apps.chat_v1.types import space as gc_space +from google.apps.chat_v1.types import space_setup, user + +from .client import ChatServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, ChatServiceTransport +from .transports.grpc_asyncio import ChatServiceGrpcAsyncIOTransport + + +class ChatServiceAsyncClient: + """Enables developers to build Chat apps and + integrations on Google Chat Platform. + """ + + _client: ChatServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ChatServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ChatServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ChatServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ChatServiceClient._DEFAULT_UNIVERSE + + attachment_path = staticmethod(ChatServiceClient.attachment_path) + parse_attachment_path = staticmethod(ChatServiceClient.parse_attachment_path) + membership_path = staticmethod(ChatServiceClient.membership_path) + parse_membership_path = staticmethod(ChatServiceClient.parse_membership_path) + message_path = staticmethod(ChatServiceClient.message_path) + parse_message_path = staticmethod(ChatServiceClient.parse_message_path) + quoted_message_metadata_path = staticmethod( + ChatServiceClient.quoted_message_metadata_path + ) + parse_quoted_message_metadata_path = staticmethod( + ChatServiceClient.parse_quoted_message_metadata_path + ) + reaction_path = staticmethod(ChatServiceClient.reaction_path) + parse_reaction_path = staticmethod(ChatServiceClient.parse_reaction_path) + space_path = staticmethod(ChatServiceClient.space_path) + parse_space_path = staticmethod(ChatServiceClient.parse_space_path) + thread_path = staticmethod(ChatServiceClient.thread_path) + parse_thread_path = staticmethod(ChatServiceClient.parse_thread_path) + common_billing_account_path = staticmethod( + ChatServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + ChatServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(ChatServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ChatServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ChatServiceClient.common_organization_path) + parse_common_organization_path = staticmethod( + ChatServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(ChatServiceClient.common_project_path) + parse_common_project_path = staticmethod( + ChatServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(ChatServiceClient.common_location_path) + parse_common_location_path = staticmethod( + ChatServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ChatServiceAsyncClient: The constructed client. + """ + return ChatServiceClient.from_service_account_info.__func__(ChatServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ChatServiceAsyncClient: The constructed client. + """ + return ChatServiceClient.from_service_account_file.__func__(ChatServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return ChatServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ChatServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ChatServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial( + type(ChatServiceClient).get_transport_class, type(ChatServiceClient) + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ChatServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the chat service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ChatServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ChatServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def create_message( + self, + request: Optional[Union[gc_message.CreateMessageRequest, dict]] = None, + *, + parent: Optional[str] = None, + message: Optional[gc_message.Message] = None, + message_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_message.Message: + r"""Creates a message in a Google Chat space. For an example, see + `Create a + message `__. + + Calling this method requires + `authentication `__ + and supports the following authentication types: + + - For text messages, user authentication or app authentication + are supported. + - For card messages, only app authentication is supported. + (Only Chat apps can create card messages.) + + .. 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.apps import chat_v1 + + async def sample_create_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CreateMessageRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_message(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.CreateMessageRequest, dict]]): + The request object. Creates a message. + parent (:class:`str`): + Required. The resource name of the space in which to + create a message. + + Format: ``spaces/{space}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message (:class:`google.apps.chat_v1.types.Message`): + Required. Message body. + This corresponds to the ``message`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message_id (:class:`str`): + Optional. A custom ID for a message. Lets Chat apps get, + update, or delete a message without needing to store the + system-assigned ID in the message's resource name + (represented in the message ``name`` field). + + The value for this field must meet the following + requirements: + + - Begins with ``client-``. For example, + ``client-custom-name`` is a valid custom ID, but + ``custom-name`` is not. + - Contains up to 63 characters and only lowercase + letters, numbers, and hyphens. + - Is unique within a space. A Chat app can't use the + same custom ID for different messages. + + For details, see `Name a + message `__. + + This corresponds to the ``message_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.apps.chat_v1.types.Message: + A message in a Google Chat space. + """ + # 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, message_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." + ) + + request = gc_message.CreateMessageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if message is not None: + request.message = message + if message_id is not None: + request.message_id = message_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_message, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 list_messages( + self, + request: Optional[Union[message.ListMessagesRequest, 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.ListMessagesAsyncPager: + r"""Lists messages in a space that the caller is a member of, + including messages from blocked members and spaces. For an + example, see `List + messages `__. Requires `user + authentication `__. + + .. 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.apps import chat_v1 + + async def sample_list_messages(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListMessagesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_messages(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.ListMessagesRequest, dict]]): + The request object. Lists messages in the specified + space, that the user is a member of. + parent (:class:`str`): + Required. The resource name of the space to list + messages from. + + Format: ``spaces/{space}`` + + 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.apps.chat_v1.services.chat_service.pagers.ListMessagesAsyncPager: + 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." + ) + + request = message.ListMessagesRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_messages, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListMessagesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_memberships( + self, + request: Optional[Union[membership.ListMembershipsRequest, 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.ListMembershipsAsyncPager: + r"""Lists memberships in a space. For an example, see `List + memberships `__. + Listing memberships with `app + authentication `__ + lists memberships in spaces that the Chat app has access to, but + excludes Chat app memberships, including its own. Listing + memberships with `User + authentication `__ + lists memberships in spaces that the authenticated user has + access to. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + .. 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.apps import chat_v1 + + async def sample_list_memberships(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListMembershipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memberships(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.ListMembershipsRequest, dict]]): + The request object. + parent (:class:`str`): + Required. The resource name of the + space for which to fetch a membership + list. + + Format: spaces/{space} + + 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.apps.chat_v1.services.chat_service.pagers.ListMembershipsAsyncPager: + 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." + ) + + request = membership.ListMembershipsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_memberships, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListMembershipsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_membership( + self, + request: Optional[Union[membership.GetMembershipRequest, 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]] = (), + ) -> membership.Membership: + r"""Returns details about a membership. For an example, see `Get a + membership `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + .. 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.apps import chat_v1 + + async def sample_get_membership(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetMembershipRequest( + name="name_value", + ) + + # Make the request + response = await client.get_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.GetMembershipRequest, dict]]): + The request object. + name (:class:`str`): + Required. Resource name of the membership to retrieve. + + To get the app's own membership, you can optionally use + ``spaces/{space}/members/app``. + + Format: ``spaces/{space}/members/{member}`` or + ``spaces/{space}/members/app`` + + When `authenticated as a + user `__, + you can use the user's email as an alias for + ``{member}``. For example, + ``spaces/{space}/members/example@gmail.com`` where + ``example@gmail.com`` is the email of the Google Chat + user. + + 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.apps.chat_v1.types.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + # 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." + ) + + request = membership.GetMembershipRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_membership, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 get_message( + self, + request: Optional[Union[message.GetMessageRequest, 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.Message: + r"""Returns details about a message. For an example, see `Read a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Note: Might return a message from a blocked member or space. + + .. 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.apps import chat_v1 + + async def sample_get_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetMessageRequest( + name="name_value", + ) + + # Make the request + response = await client.get_message(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.GetMessageRequest, dict]]): + The request object. + name (:class:`str`): + Required. Resource name of the message. + + Format: ``spaces/{space}/messages/{message}`` + + If you've set a custom ID for your message, you can use + the value from the ``clientAssignedMessageId`` field for + ``{message}``. For details, see [Name a message] + (https://developers.google.com/chat/api/guides/v1/messages/create#name_a_created_message). + + 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.apps.chat_v1.types.Message: + A message in a Google Chat space. + """ + # 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." + ) + + request = message.GetMessageRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_message, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 update_message( + self, + request: Optional[Union[gc_message.UpdateMessageRequest, dict]] = None, + *, + message: Optional[gc_message.Message] = 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]] = (), + ) -> gc_message.Message: + r"""Updates a message. There's a difference between the ``patch`` + and ``update`` methods. The ``patch`` method uses a ``patch`` + request while the ``update`` method uses a ``put`` request. We + recommend using the ``patch`` method. For an example, see + `Update a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + When using app authentication, requests can only update messages + created by the calling Chat app. + + .. 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.apps import chat_v1 + + async def sample_update_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UpdateMessageRequest( + ) + + # Make the request + response = await client.update_message(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.UpdateMessageRequest, dict]]): + The request object. + message (:class:`google.apps.chat_v1.types.Message`): + Required. Message with fields + updated. + + This corresponds to the ``message`` 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 field paths to update. Separate multiple + values with commas or use ``*`` to update all field + paths. + + Currently supported field paths: + + - ``text`` + + - ``attachment`` + + - ``cards`` (Requires `app + authentication `__.) + + - ``cards_v2`` (Requires `app + authentication `__.) + + - Developer Preview: ``accessory_widgets`` (Requires + `app + authentication `__.) + + 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.apps.chat_v1.types.Message: + A message in a Google Chat space. + """ + # 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, 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." + ) + + request = gc_message.UpdateMessageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if message is not None: + request.message = message + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_message, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("message.name", request.message.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 delete_message( + self, + request: Optional[Union[message.DeleteMessageRequest, 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]] = (), + ) -> None: + r"""Deletes a message. For an example, see `Delete a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + When using app authentication, requests can only delete messages + created by the calling Chat app. + + .. 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.apps import chat_v1 + + async def sample_delete_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMessageRequest( + name="name_value", + ) + + # Make the request + await client.delete_message(request=request) + + Args: + request (Optional[Union[google.apps.chat_v1.types.DeleteMessageRequest, dict]]): + The request object. + name (:class:`str`): + Required. Resource name of the message. + + Format: ``spaces/{space}/messages/{message}`` + + If you've set a custom ID for your message, you can use + the value from the ``clientAssignedMessageId`` field for + ``{message}``. For details, see [Name a message] + (https://developers.google.com/chat/api/guides/v1/messages/create#name_a_created_message). + + 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. + """ + # 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." + ) + + request = message.DeleteMessageRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_message, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_attachment( + self, + request: Optional[Union[attachment.GetAttachmentRequest, 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]] = (), + ) -> attachment.Attachment: + r"""Gets the metadata of a message attachment. The attachment data + is fetched using the `media + API `__. + For an example, see `Get a message + attachment `__. + Requires `app + authentication `__. + + .. 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.apps import chat_v1 + + async def sample_get_attachment(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetAttachmentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attachment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.GetAttachmentRequest, dict]]): + The request object. + name (:class:`str`): + Required. Resource name of the attachment, in the form + ``spaces/*/messages/*/attachments/*``. + + 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.apps.chat_v1.types.Attachment: + An attachment in Google Chat. + """ + # 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." + ) + + request = attachment.GetAttachmentRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_attachment, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 upload_attachment( + self, + request: Optional[Union[attachment.UploadAttachmentRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> attachment.UploadAttachmentResponse: + r"""Uploads an attachment. For an example, see `Upload media as a + file + attachment `__. + Requires user + `authentication `__. + + You can upload attachments up to 200 MB. Certain file types + aren't supported. For details, see `File types blocked by Google + Chat `__. + + .. 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.apps import chat_v1 + + async def sample_upload_attachment(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UploadAttachmentRequest( + parent="parent_value", + filename="filename_value", + ) + + # Make the request + response = await client.upload_attachment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.UploadAttachmentRequest, dict]]): + The request object. + 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.apps.chat_v1.types.UploadAttachmentResponse: + + """ + # Create or coerce a protobuf request object. + request = attachment.UploadAttachmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.upload_attachment, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 list_spaces( + self, + request: Optional[Union[space.ListSpacesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSpacesAsyncPager: + r"""Lists spaces the caller is a member of. Group chats and DMs + aren't listed until the first message is sent. For an example, + see `List + spaces `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Lists spaces visible to the caller or authenticated user. Group + chats and DMs aren't listed until the first message is sent. + + .. 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.apps import chat_v1 + + async def sample_list_spaces(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListSpacesRequest( + ) + + # Make the request + page_result = client.list_spaces(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.ListSpacesRequest, dict]]): + The request object. A request to list the spaces the + caller is a member of. + 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.apps.chat_v1.services.chat_service.pagers.ListSpacesAsyncPager: + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + request = space.ListSpacesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_spaces, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListSpacesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_space( + self, + request: Optional[Union[space.GetSpaceRequest, 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]] = (), + ) -> space.Space: + r"""Returns details about a space. For an example, see `Get a + space `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + .. 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.apps import chat_v1 + + async def sample_get_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetSpaceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_space(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.GetSpaceRequest, dict]]): + The request object. A request to return a single space. + name (:class:`str`): + Required. Resource name of the space, in the form + `spaces/*`. + + Format: ``spaces/{space}`` + + 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.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # 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." + ) + + request = space.GetSpaceRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_space, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 create_space( + self, + request: Optional[Union[gc_space.CreateSpaceRequest, dict]] = None, + *, + space: Optional[gc_space.Space] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_space.Space: + r"""Creates a named space. Spaces grouped by topics aren't + supported. For an example, see `Create a + space `__. + + If you receive the error message ``ALREADY_EXISTS`` when + creating a space, try a different ``displayName``. An existing + space within the Google Workspace organization might already use + this display name. + + Requires `user + authentication `__. + + .. 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.apps import chat_v1 + + async def sample_create_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CreateSpaceRequest( + ) + + # Make the request + response = await client.create_space(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.CreateSpaceRequest, dict]]): + The request object. + space (:class:`google.apps.chat_v1.types.Space`): + Required. The ``displayName`` and ``spaceType`` fields + must be populated. Only ``SpaceType.SPACE`` is + supported. + + If you receive the error message ``ALREADY_EXISTS`` when + creating a space, try a different ``displayName``. An + existing space within the Google Workspace organization + might already use this display name. + + The space ``name`` is assigned on the server so anything + specified in this field will be ignored. + + This corresponds to the ``space`` 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.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # 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([space]) + 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." + ) + + request = gc_space.CreateSpaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if space is not None: + request.space = space + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_space, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 set_up_space( + self, + request: Optional[Union[space_setup.SetUpSpaceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.Space: + r"""Creates a space and adds specified users to it. The calling user + is automatically added to the space, and shouldn't be specified + as a membership in the request. For an example, see `Set up a + space `__. + + To specify the human members to add, add memberships with the + appropriate ``member.name`` in the ``SetUpSpaceRequest``. To add + a human user, use ``users/{user}``, where ``{user}`` can be the + email address for the user. For users in the same Workspace + organization ``{user}`` can also be the ``id`` for the person + from the People API, or the ``id`` for the user in the Directory + API. For example, if the People API Person profile ID for + ``user@example.com`` is ``123456789``, you can add the user to + the space by setting the ``membership.member.name`` to + ``users/user@example.com`` or ``users/123456789``. + + For a space or group chat, if the caller blocks or is blocked by + some members, then those members aren't added to the created + space. + + To create a direct message (DM) between the calling user and + another human user, specify exactly one membership to represent + the human user. If one user blocks the other, the request fails + and the DM isn't created. + + To create a DM between the calling user and the calling app, set + ``Space.singleUserBotDm`` to ``true`` and don't specify any + memberships. You can only use this method to set up a DM with + the calling app. To add the calling app as a member of a space + or an existing DM between two human users, see `create a + membership `__. + + If a DM already exists between two users, even when one user + blocks the other at the time a request is made, then the + existing DM is returned. + + Spaces with threaded replies aren't supported. If you receive + the error message ``ALREADY_EXISTS`` when setting up a space, + try a different ``displayName``. An existing space within the + Google Workspace organization might already use this display + name. + + Requires `user + authentication `__. + + .. 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.apps import chat_v1 + + async def sample_set_up_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.SetUpSpaceRequest( + ) + + # Make the request + response = await client.set_up_space(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.SetUpSpaceRequest, dict]]): + The request object. + 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.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # Create or coerce a protobuf request object. + request = space_setup.SetUpSpaceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_up_space, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 update_space( + self, + request: Optional[Union[gc_space.UpdateSpaceRequest, dict]] = None, + *, + space: Optional[gc_space.Space] = 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]] = (), + ) -> gc_space.Space: + r"""Updates a space. For an example, see `Update a + space `__. + + If you're updating the ``displayName`` field and receive the + error message ``ALREADY_EXISTS``, try a different display name.. + An existing space within the Google Workspace organization might + already use this display name. + + Requires `user + authentication `__. + + .. 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.apps import chat_v1 + + async def sample_update_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UpdateSpaceRequest( + ) + + # Make the request + response = await client.update_space(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.UpdateSpaceRequest, dict]]): + The request object. A request to update a single space. + space (:class:`google.apps.chat_v1.types.Space`): + Required. Space with fields to be updated. + ``Space.name`` must be populated in the form of + ``spaces/{space}``. Only fields specified by + ``update_mask`` are updated. + + This corresponds to the ``space`` 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 updated field paths, comma separated if + there are multiple. + + Currently supported field paths: + + - ``display_name`` (Only supports changing the display + name of a space with the ``SPACE`` type, or when also + including the ``space_type`` mask to change a + ``GROUP_CHAT`` space type to ``SPACE``. Trying to + update the display name of a ``GROUP_CHAT`` or a + ``DIRECT_MESSAGE`` space results in an invalid + argument error. If you receive the error message + ``ALREADY_EXISTS`` when updating the ``displayName``, + try a different ``displayName``. An existing space + within the Google Workspace organization might + already use this display name.) + + - ``space_type`` (Only supports changing a + ``GROUP_CHAT`` space type to ``SPACE``. Include + ``display_name`` together with ``space_type`` in the + update mask and ensure that the specified space has a + non-empty display name and the ``SPACE`` space type. + Including the ``space_type`` mask and the ``SPACE`` + type in the specified space when updating the display + name is optional if the existing space already has + the ``SPACE`` type. Trying to update the space type + in other ways results in an invalid argument error). + + - ``space_details`` + + - ``space_history_state`` (Supports `turning history on + or off for the + space `__ + if `the organization allows users to change their + history + setting `__. + Warning: mutually exclusive with all other field + paths.) + + - Developer Preview: ``access_settings.audience`` + (Supports changing the `access + setting `__ + of a space. If no audience is specified in the access + setting, the space's access setting is updated to + restricted. Warning: mutually exclusive with all + other field paths.) + + 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.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # 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([space, 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." + ) + + request = gc_space.UpdateSpaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if space is not None: + request.space = space + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_space, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("space.name", request.space.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 delete_space( + self, + request: Optional[Union[space.DeleteSpaceRequest, 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]] = (), + ) -> None: + r"""Deletes a named space. Always performs a cascading delete, which + means that the space's child resources—like messages posted in + the space and memberships in the space—are also deleted. For an + example, see `Delete a + space `__. + Requires `user + authentication `__ + from a user who has permission to delete the space. + + .. 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.apps import chat_v1 + + async def sample_delete_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteSpaceRequest( + name="name_value", + ) + + # Make the request + await client.delete_space(request=request) + + Args: + request (Optional[Union[google.apps.chat_v1.types.DeleteSpaceRequest, dict]]): + The request object. Request for deleting a space. + name (:class:`str`): + Required. Resource name of the space to delete. + + Format: ``spaces/{space}`` + + 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. + """ + # 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." + ) + + request = space.DeleteSpaceRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_space, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def complete_import_space( + self, + request: Optional[Union[space.CompleteImportSpaceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.CompleteImportSpaceResponse: + r"""Completes the `import + process `__ + for the specified space and makes it visible to users. Requires + app authentication and domain-wide delegation. For more + information, see `Authorize Google Chat apps to import + data `__. + + .. 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.apps import chat_v1 + + async def sample_complete_import_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CompleteImportSpaceRequest( + name="name_value", + ) + + # Make the request + response = await client.complete_import_space(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.CompleteImportSpaceRequest, dict]]): + The request object. Request message for completing the + import process for a space. + 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.apps.chat_v1.types.CompleteImportSpaceResponse: + + """ + # Create or coerce a protobuf request object. + request = space.CompleteImportSpaceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.complete_import_space, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 find_direct_message( + self, + request: Optional[Union[space.FindDirectMessageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.Space: + r"""Returns the existing direct message with the specified user. If + no direct message space is found, returns a ``404 NOT_FOUND`` + error. For an example, see `Find a direct + message `__. + + With `user + authentication `__, + returns the direct message space between the specified user and + the authenticated user. + + With `app + authentication `__, + returns the direct message space between the specified user and + the calling Chat app. + + Requires `user + authentication `__ + or `app + authentication `__. + + .. 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.apps import chat_v1 + + async def sample_find_direct_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.FindDirectMessageRequest( + name="name_value", + ) + + # Make the request + response = await client.find_direct_message(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.FindDirectMessageRequest, dict]]): + The request object. A request to get direct message space + based on the user resource. + 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.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # Create or coerce a protobuf request object. + request = space.FindDirectMessageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.find_direct_message, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 create_membership( + self, + request: Optional[Union[gc_membership.CreateMembershipRequest, dict]] = None, + *, + parent: Optional[str] = None, + membership: Optional[gc_membership.Membership] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_membership.Membership: + r"""Creates a human membership or app membership for the calling + app. Creating memberships for other apps isn't supported. For an + example, see `Create a + membership `__. + When creating a membership, if the specified member has their + auto-accept policy turned off, then they're invited, and must + accept the space invitation before joining. Otherwise, creating + a membership adds the member directly to the specified space. + Requires `user + authentication `__. + + To specify the member to add, set the ``membership.member.name`` + in the ``CreateMembershipRequest``: + + - To add the calling app to a space or a direct message between + two human users, use ``users/app``. Unable to add other apps + to the space. + + - To add a human user, use ``users/{user}``, where ``{user}`` + can be the email address for the user. For users in the same + Workspace organization ``{user}`` can also be the ``id`` for + the person from the People API, or the ``id`` for the user in + the Directory API. For example, if the People API Person + profile ID for ``user@example.com`` is ``123456789``, you can + add the user to the space by setting the + ``membership.member.name`` to ``users/user@example.com`` or + ``users/123456789``. + + .. 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.apps import chat_v1 + + async def sample_create_membership(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CreateMembershipRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.CreateMembershipRequest, dict]]): + The request object. + parent (:class:`str`): + Required. The resource name of the + space for which to create the + membership. + + Format: spaces/{space} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + membership (:class:`google.apps.chat_v1.types.Membership`): + Required. The membership relation to create. The + ``memberType`` field must contain a user with the + ``user.name`` and ``user.type`` fields populated. The + server will assign a resource name and overwrite + anything specified. When a Chat app creates a membership + relation for a human user, it must use the + ``chat.memberships`` scope, set ``user.type`` to + ``HUMAN``, and set ``user.name`` with format + ``users/{user}``, where ``{user}`` can be the email + address for the user. For users in the same Workspace + organization ``{user}`` can also be the ``id`` of the + `person `__ + from the People API, or the ``id`` for the user in the + Directory API. For example, if the People API Person + profile ID for ``user@example.com`` is ``123456789``, + you can add the user to the space by setting the + ``membership.member.name`` to ``users/user@example.com`` + or ``users/123456789``. When a Chat app creates a + membership relation for itself, it must use the + ``chat.memberships.app`` scope, set ``user.type`` to + ``BOT``, and set ``user.name`` to ``users/app``. + + This corresponds to the ``membership`` 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.apps.chat_v1.types.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + # 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, membership]) + 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." + ) + + request = gc_membership.CreateMembershipRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if membership is not None: + request.membership = membership + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_membership, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 delete_membership( + self, + request: Optional[Union[membership.DeleteMembershipRequest, 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]] = (), + ) -> membership.Membership: + r"""Deletes a membership. For an example, see `Delete a + membership `__. + + Requires `user + authentication `__. + + .. 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.apps import chat_v1 + + async def sample_delete_membership(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMembershipRequest( + name="name_value", + ) + + # Make the request + response = await client.delete_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.DeleteMembershipRequest, dict]]): + The request object. + name (:class:`str`): + Required. Resource name of the membership to delete. + Chat apps can delete human users' or their own + memberships. Chat apps can't delete other apps' + memberships. + + When deleting a human membership, requires the + ``chat.memberships`` scope and + ``spaces/{space}/members/{member}`` format. You can use + the email as an alias for ``{member}``. For example, + ``spaces/{space}/members/example@gmail.com`` where + ``example@gmail.com`` is the email of the Google Chat + user. + + When deleting an app membership, requires the + ``chat.memberships.app`` scope and + ``spaces/{space}/members/app`` format. + + Format: ``spaces/{space}/members/{member}`` or + ``spaces/{space}/members/app``. + + 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.apps.chat_v1.types.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + # 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." + ) + + request = membership.DeleteMembershipRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_membership, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 create_reaction( + self, + request: Optional[Union[gc_reaction.CreateReactionRequest, dict]] = None, + *, + parent: Optional[str] = None, + reaction: Optional[gc_reaction.Reaction] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_reaction.Reaction: + r"""Creates a reaction and adds it to a message. For an example, see + `Create a + reaction `__. + Requires `user + authentication `__. + Only unicode emoji are supported. + + .. 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.apps import chat_v1 + + async def sample_create_reaction(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CreateReactionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_reaction(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.CreateReactionRequest, dict]]): + The request object. Creates a reaction to a message. + parent (:class:`str`): + Required. The message where the reaction is created. + + Format: ``spaces/{space}/messages/{message}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reaction (:class:`google.apps.chat_v1.types.Reaction`): + Required. The reaction to create. + This corresponds to the ``reaction`` 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.apps.chat_v1.types.Reaction: + A reaction to a message. + """ + # 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, reaction]) + 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." + ) + + request = gc_reaction.CreateReactionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if reaction is not None: + request.reaction = reaction + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_reaction, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 list_reactions( + self, + request: Optional[Union[reaction.ListReactionsRequest, 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.ListReactionsAsyncPager: + r"""Lists reactions to a message. For an example, see `List + reactions `__. + Requires `user + authentication `__. + + .. 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.apps import chat_v1 + + async def sample_list_reactions(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListReactionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_reactions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.apps.chat_v1.types.ListReactionsRequest, dict]]): + The request object. Lists reactions to a message. + parent (:class:`str`): + Required. The message users reacted to. + + Format: ``spaces/{space}/messages/{message}`` + + 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.apps.chat_v1.services.chat_service.pagers.ListReactionsAsyncPager: + 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." + ) + + request = reaction.ListReactionsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_reactions, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListReactionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_reaction( + self, + request: Optional[Union[reaction.DeleteReactionRequest, 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]] = (), + ) -> None: + r"""Deletes a reaction to a message. For an example, see `Delete a + reaction `__. + Requires `user + authentication `__. + + .. 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.apps import chat_v1 + + async def sample_delete_reaction(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteReactionRequest( + name="name_value", + ) + + # Make the request + await client.delete_reaction(request=request) + + Args: + request (Optional[Union[google.apps.chat_v1.types.DeleteReactionRequest, dict]]): + The request object. Deletes a reaction to a message. + name (:class:`str`): + Required. Name of the reaction to delete. + + Format: + ``spaces/{space}/messages/{message}/reactions/{reaction}`` + + 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. + """ + # 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." + ) + + request = reaction.DeleteReactionRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_reaction, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "ChatServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("ChatServiceAsyncClient",) 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 new file mode 100644 index 000000000000..ebf4ea5063be --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py @@ -0,0 +1,3451 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.apps.chat_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.apps.chat_v1.services.chat_service import pagers +from google.apps.chat_v1.types import ( + annotation, + attachment, + contextual_addon, + deletion_metadata, + group, + history_state, + matched_url, +) +from google.apps.chat_v1.types import membership +from google.apps.chat_v1.types import membership as gc_membership +from google.apps.chat_v1.types import message +from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import slash_command +from google.apps.chat_v1.types import space +from google.apps.chat_v1.types import space as gc_space +from google.apps.chat_v1.types import space_setup, user + +from .transports.base import DEFAULT_CLIENT_INFO, ChatServiceTransport +from .transports.grpc import ChatServiceGrpcTransport +from .transports.grpc_asyncio import ChatServiceGrpcAsyncIOTransport +from .transports.rest import ChatServiceRestTransport + + +class ChatServiceClientMeta(type): + """Metaclass for the ChatService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[ChatServiceTransport]] + _transport_registry["grpc"] = ChatServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ChatServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ChatServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ChatServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ChatServiceClient(metaclass=ChatServiceClientMeta): + """Enables developers to build Chat apps and + integrations on Google Chat Platform. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "chat.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "chat.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ChatServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ChatServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ChatServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ChatServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def attachment_path( + space: str, + message: str, + attachment: str, + ) -> str: + """Returns a fully-qualified attachment string.""" + return "spaces/{space}/messages/{message}/attachments/{attachment}".format( + space=space, + message=message, + attachment=attachment, + ) + + @staticmethod + def parse_attachment_path(path: str) -> Dict[str, str]: + """Parses a attachment path into its component segments.""" + m = re.match( + r"^spaces/(?P.+?)/messages/(?P.+?)/attachments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def membership_path( + space: str, + member: str, + ) -> str: + """Returns a fully-qualified membership string.""" + return "spaces/{space}/members/{member}".format( + space=space, + member=member, + ) + + @staticmethod + def parse_membership_path(path: str) -> Dict[str, str]: + """Parses a membership path into its component segments.""" + m = re.match(r"^spaces/(?P.+?)/members/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def message_path( + space: str, + message: str, + ) -> str: + """Returns a fully-qualified message string.""" + return "spaces/{space}/messages/{message}".format( + space=space, + message=message, + ) + + @staticmethod + def parse_message_path(path: str) -> Dict[str, str]: + """Parses a message path into its component segments.""" + m = re.match(r"^spaces/(?P.+?)/messages/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def quoted_message_metadata_path( + space: str, + message: str, + quoted_message_metadata: str, + ) -> str: + """Returns a fully-qualified quoted_message_metadata string.""" + return "spaces/{space}/messages/{message}/quotedMessageMetadata/{quoted_message_metadata}".format( + space=space, + message=message, + quoted_message_metadata=quoted_message_metadata, + ) + + @staticmethod + def parse_quoted_message_metadata_path(path: str) -> Dict[str, str]: + """Parses a quoted_message_metadata path into its component segments.""" + m = re.match( + r"^spaces/(?P.+?)/messages/(?P.+?)/quotedMessageMetadata/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def reaction_path( + space: str, + message: str, + reaction: str, + ) -> str: + """Returns a fully-qualified reaction string.""" + return "spaces/{space}/messages/{message}/reactions/{reaction}".format( + space=space, + message=message, + reaction=reaction, + ) + + @staticmethod + def parse_reaction_path(path: str) -> Dict[str, str]: + """Parses a reaction path into its component segments.""" + m = re.match( + r"^spaces/(?P.+?)/messages/(?P.+?)/reactions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def space_path( + space: str, + ) -> str: + """Returns a fully-qualified space string.""" + return "spaces/{space}".format( + space=space, + ) + + @staticmethod + def parse_space_path(path: str) -> Dict[str, str]: + """Parses a space path into its component segments.""" + m = re.match(r"^spaces/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def thread_path( + space: str, + thread: str, + ) -> str: + """Returns a fully-qualified thread string.""" + return "spaces/{space}/threads/{thread}".format( + space=space, + thread=thread, + ) + + @staticmethod + def parse_thread_path(path: str) -> Dict[str, str]: + """Parses a thread path into its component segments.""" + m = re.match(r"^spaces/(?P.+?)/threads/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = ChatServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = ChatServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ChatServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = ChatServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + 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. + + Returns: + bool: True iff the configured universe domain is valid. + + 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 + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ChatServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the chat service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ChatServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = ChatServiceClient._read_environment_variables() + self._client_cert_source = ChatServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = ChatServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, ChatServiceTransport) + if transport_provided: + # transport is a ChatServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(ChatServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or ChatServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + Transport = type(self).get_transport_class(cast(str, transport)) + self._transport = Transport( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def create_message( + self, + request: Optional[Union[gc_message.CreateMessageRequest, dict]] = None, + *, + parent: Optional[str] = None, + message: Optional[gc_message.Message] = None, + message_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_message.Message: + r"""Creates a message in a Google Chat space. For an example, see + `Create a + message `__. + + Calling this method requires + `authentication `__ + and supports the following authentication types: + + - For text messages, user authentication or app authentication + are supported. + - For card messages, only app authentication is supported. + (Only Chat apps can create card messages.) + + .. 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.apps import chat_v1 + + def sample_create_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CreateMessageRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_message(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.CreateMessageRequest, dict]): + The request object. Creates a message. + parent (str): + Required. The resource name of the space in which to + create a message. + + Format: ``spaces/{space}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message (google.apps.chat_v1.types.Message): + Required. Message body. + This corresponds to the ``message`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + message_id (str): + Optional. A custom ID for a message. Lets Chat apps get, + update, or delete a message without needing to store the + system-assigned ID in the message's resource name + (represented in the message ``name`` field). + + The value for this field must meet the following + requirements: + + - Begins with ``client-``. For example, + ``client-custom-name`` is a valid custom ID, but + ``custom-name`` is not. + - Contains up to 63 characters and only lowercase + letters, numbers, and hyphens. + - Is unique within a space. A Chat app can't use the + same custom ID for different messages. + + For details, see `Name a + message `__. + + This corresponds to the ``message_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.apps.chat_v1.types.Message: + A message in a Google Chat space. + """ + # 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, message_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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a gc_message.CreateMessageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gc_message.CreateMessageRequest): + request = gc_message.CreateMessageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if message is not None: + request.message = message + if message_id is not None: + request.message_id = message_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_message] + + # 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 list_messages( + self, + request: Optional[Union[message.ListMessagesRequest, 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.ListMessagesPager: + r"""Lists messages in a space that the caller is a member of, + including messages from blocked members and spaces. For an + example, see `List + messages `__. Requires `user + authentication `__. + + .. 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.apps import chat_v1 + + def sample_list_messages(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListMessagesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_messages(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.apps.chat_v1.types.ListMessagesRequest, dict]): + The request object. Lists messages in the specified + space, that the user is a member of. + parent (str): + Required. The resource name of the space to list + messages from. + + Format: ``spaces/{space}`` + + 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.apps.chat_v1.services.chat_service.pagers.ListMessagesPager: + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a message.ListMessagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, message.ListMessagesRequest): + request = message.ListMessagesRequest(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_messages] + + # 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.ListMessagesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_memberships( + self, + request: Optional[Union[membership.ListMembershipsRequest, 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.ListMembershipsPager: + r"""Lists memberships in a space. For an example, see `List + memberships `__. + Listing memberships with `app + authentication `__ + lists memberships in spaces that the Chat app has access to, but + excludes Chat app memberships, including its own. Listing + memberships with `User + authentication `__ + lists memberships in spaces that the authenticated user has + access to. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + .. 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.apps import chat_v1 + + def sample_list_memberships(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListMembershipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memberships(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.apps.chat_v1.types.ListMembershipsRequest, dict]): + The request object. + parent (str): + Required. The resource name of the + space for which to fetch a membership + list. + + Format: spaces/{space} + + 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.apps.chat_v1.services.chat_service.pagers.ListMembershipsPager: + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a membership.ListMembershipsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, membership.ListMembershipsRequest): + request = membership.ListMembershipsRequest(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_memberships] + + # 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.ListMembershipsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_membership( + self, + request: Optional[Union[membership.GetMembershipRequest, 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]] = (), + ) -> membership.Membership: + r"""Returns details about a membership. For an example, see `Get a + membership `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + .. 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.apps import chat_v1 + + def sample_get_membership(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetMembershipRequest( + name="name_value", + ) + + # Make the request + response = client.get_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.GetMembershipRequest, dict]): + The request object. + name (str): + Required. Resource name of the membership to retrieve. + + To get the app's own membership, you can optionally use + ``spaces/{space}/members/app``. + + Format: ``spaces/{space}/members/{member}`` or + ``spaces/{space}/members/app`` + + When `authenticated as a + user `__, + you can use the user's email as an alias for + ``{member}``. For example, + ``spaces/{space}/members/example@gmail.com`` where + ``example@gmail.com`` is the email of the Google Chat + user. + + 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.apps.chat_v1.types.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a membership.GetMembershipRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, membership.GetMembershipRequest): + request = membership.GetMembershipRequest(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_membership] + + # 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 get_message( + self, + request: Optional[Union[message.GetMessageRequest, 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.Message: + r"""Returns details about a message. For an example, see `Read a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Note: Might return a message from a blocked member or space. + + .. 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.apps import chat_v1 + + def sample_get_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetMessageRequest( + name="name_value", + ) + + # Make the request + response = client.get_message(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.GetMessageRequest, dict]): + The request object. + name (str): + Required. Resource name of the message. + + Format: ``spaces/{space}/messages/{message}`` + + If you've set a custom ID for your message, you can use + the value from the ``clientAssignedMessageId`` field for + ``{message}``. For details, see [Name a message] + (https://developers.google.com/chat/api/guides/v1/messages/create#name_a_created_message). + + 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.apps.chat_v1.types.Message: + A message in a Google Chat space. + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a message.GetMessageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, message.GetMessageRequest): + request = message.GetMessageRequest(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] + + # 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 update_message( + self, + request: Optional[Union[gc_message.UpdateMessageRequest, dict]] = None, + *, + message: Optional[gc_message.Message] = 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]] = (), + ) -> gc_message.Message: + r"""Updates a message. There's a difference between the ``patch`` + and ``update`` methods. The ``patch`` method uses a ``patch`` + request while the ``update`` method uses a ``put`` request. We + recommend using the ``patch`` method. For an example, see + `Update a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + When using app authentication, requests can only update messages + created by the calling Chat app. + + .. 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.apps import chat_v1 + + def sample_update_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UpdateMessageRequest( + ) + + # Make the request + response = client.update_message(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.UpdateMessageRequest, dict]): + The request object. + message (google.apps.chat_v1.types.Message): + Required. Message with fields + updated. + + This corresponds to the ``message`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The field paths to update. Separate multiple + values with commas or use ``*`` to update all field + paths. + + Currently supported field paths: + + - ``text`` + + - ``attachment`` + + - ``cards`` (Requires `app + authentication `__.) + + - ``cards_v2`` (Requires `app + authentication `__.) + + - Developer Preview: ``accessory_widgets`` (Requires + `app + authentication `__.) + + 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.apps.chat_v1.types.Message: + A message in a Google Chat space. + """ + # 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, 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a gc_message.UpdateMessageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gc_message.UpdateMessageRequest): + request = gc_message.UpdateMessageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if message is not None: + request.message = message + 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] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("message.name", request.message.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 delete_message( + self, + request: Optional[Union[message.DeleteMessageRequest, 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]] = (), + ) -> None: + r"""Deletes a message. For an example, see `Delete a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + When using app authentication, requests can only delete messages + created by the calling Chat app. + + .. 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.apps import chat_v1 + + def sample_delete_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMessageRequest( + name="name_value", + ) + + # Make the request + client.delete_message(request=request) + + Args: + request (Union[google.apps.chat_v1.types.DeleteMessageRequest, dict]): + The request object. + name (str): + Required. Resource name of the message. + + Format: ``spaces/{space}/messages/{message}`` + + If you've set a custom ID for your message, you can use + the value from the ``clientAssignedMessageId`` field for + ``{message}``. For details, see [Name a message] + (https://developers.google.com/chat/api/guides/v1/messages/create#name_a_created_message). + + 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. + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a message.DeleteMessageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, message.DeleteMessageRequest): + request = message.DeleteMessageRequest(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_message] + + # 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_attachment( + self, + request: Optional[Union[attachment.GetAttachmentRequest, 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]] = (), + ) -> attachment.Attachment: + r"""Gets the metadata of a message attachment. The attachment data + is fetched using the `media + API `__. + For an example, see `Get a message + attachment `__. + Requires `app + authentication `__. + + .. 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.apps import chat_v1 + + def sample_get_attachment(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetAttachmentRequest( + name="name_value", + ) + + # Make the request + response = client.get_attachment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.GetAttachmentRequest, dict]): + The request object. + name (str): + Required. Resource name of the attachment, in the form + ``spaces/*/messages/*/attachments/*``. + + 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.apps.chat_v1.types.Attachment: + An attachment in Google Chat. + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a attachment.GetAttachmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, attachment.GetAttachmentRequest): + request = attachment.GetAttachmentRequest(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_attachment] + + # 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 upload_attachment( + self, + request: Optional[Union[attachment.UploadAttachmentRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> attachment.UploadAttachmentResponse: + r"""Uploads an attachment. For an example, see `Upload media as a + file + attachment `__. + Requires user + `authentication `__. + + You can upload attachments up to 200 MB. Certain file types + aren't supported. For details, see `File types blocked by Google + Chat `__. + + .. 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.apps import chat_v1 + + def sample_upload_attachment(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UploadAttachmentRequest( + parent="parent_value", + filename="filename_value", + ) + + # Make the request + response = client.upload_attachment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.UploadAttachmentRequest, dict]): + The request 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. + + Returns: + google.apps.chat_v1.types.UploadAttachmentResponse: + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a attachment.UploadAttachmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, attachment.UploadAttachmentRequest): + request = attachment.UploadAttachmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.upload_attachment] + + # 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 list_spaces( + self, + request: Optional[Union[space.ListSpacesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSpacesPager: + r"""Lists spaces the caller is a member of. Group chats and DMs + aren't listed until the first message is sent. For an example, + see `List + spaces `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Lists spaces visible to the caller or authenticated user. Group + chats and DMs aren't listed until the first message is sent. + + .. 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.apps import chat_v1 + + def sample_list_spaces(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListSpacesRequest( + ) + + # Make the request + page_result = client.list_spaces(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.apps.chat_v1.types.ListSpacesRequest, dict]): + The request object. A request to list the spaces the + caller is a member of. + 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.apps.chat_v1.services.chat_service.pagers.ListSpacesPager: + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a space.ListSpacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, space.ListSpacesRequest): + request = space.ListSpacesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_spaces] + + # 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.ListSpacesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_space( + self, + request: Optional[Union[space.GetSpaceRequest, 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]] = (), + ) -> space.Space: + r"""Returns details about a space. For an example, see `Get a + space `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + .. 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.apps import chat_v1 + + def sample_get_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetSpaceRequest( + name="name_value", + ) + + # Make the request + response = client.get_space(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.GetSpaceRequest, dict]): + The request object. A request to return a single space. + name (str): + Required. Resource name of the space, in the form + `spaces/*`. + + Format: ``spaces/{space}`` + + 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.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a space.GetSpaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, space.GetSpaceRequest): + request = space.GetSpaceRequest(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_space] + + # 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 create_space( + self, + request: Optional[Union[gc_space.CreateSpaceRequest, dict]] = None, + *, + space: Optional[gc_space.Space] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_space.Space: + r"""Creates a named space. Spaces grouped by topics aren't + supported. For an example, see `Create a + space `__. + + If you receive the error message ``ALREADY_EXISTS`` when + creating a space, try a different ``displayName``. An existing + space within the Google Workspace organization might already use + this display name. + + Requires `user + authentication `__. + + .. 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.apps import chat_v1 + + def sample_create_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CreateSpaceRequest( + ) + + # Make the request + response = client.create_space(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.CreateSpaceRequest, dict]): + The request object. + space (google.apps.chat_v1.types.Space): + Required. The ``displayName`` and ``spaceType`` fields + must be populated. Only ``SpaceType.SPACE`` is + supported. + + If you receive the error message ``ALREADY_EXISTS`` when + creating a space, try a different ``displayName``. An + existing space within the Google Workspace organization + might already use this display name. + + The space ``name`` is assigned on the server so anything + specified in this field will be ignored. + + This corresponds to the ``space`` 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.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # 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([space]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a gc_space.CreateSpaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gc_space.CreateSpaceRequest): + request = gc_space.CreateSpaceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if space is not None: + request.space = space + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_space] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_up_space( + self, + request: Optional[Union[space_setup.SetUpSpaceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.Space: + r"""Creates a space and adds specified users to it. The calling user + is automatically added to the space, and shouldn't be specified + as a membership in the request. For an example, see `Set up a + space `__. + + To specify the human members to add, add memberships with the + appropriate ``member.name`` in the ``SetUpSpaceRequest``. To add + a human user, use ``users/{user}``, where ``{user}`` can be the + email address for the user. For users in the same Workspace + organization ``{user}`` can also be the ``id`` for the person + from the People API, or the ``id`` for the user in the Directory + API. For example, if the People API Person profile ID for + ``user@example.com`` is ``123456789``, you can add the user to + the space by setting the ``membership.member.name`` to + ``users/user@example.com`` or ``users/123456789``. + + For a space or group chat, if the caller blocks or is blocked by + some members, then those members aren't added to the created + space. + + To create a direct message (DM) between the calling user and + another human user, specify exactly one membership to represent + the human user. If one user blocks the other, the request fails + and the DM isn't created. + + To create a DM between the calling user and the calling app, set + ``Space.singleUserBotDm`` to ``true`` and don't specify any + memberships. You can only use this method to set up a DM with + the calling app. To add the calling app as a member of a space + or an existing DM between two human users, see `create a + membership `__. + + If a DM already exists between two users, even when one user + blocks the other at the time a request is made, then the + existing DM is returned. + + Spaces with threaded replies aren't supported. If you receive + the error message ``ALREADY_EXISTS`` when setting up a space, + try a different ``displayName``. An existing space within the + Google Workspace organization might already use this display + name. + + Requires `user + authentication `__. + + .. 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.apps import chat_v1 + + def sample_set_up_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.SetUpSpaceRequest( + ) + + # Make the request + response = client.set_up_space(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.SetUpSpaceRequest, dict]): + The request 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. + + Returns: + google.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a space_setup.SetUpSpaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, space_setup.SetUpSpaceRequest): + request = space_setup.SetUpSpaceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_up_space] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_space( + self, + request: Optional[Union[gc_space.UpdateSpaceRequest, dict]] = None, + *, + space: Optional[gc_space.Space] = 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]] = (), + ) -> gc_space.Space: + r"""Updates a space. For an example, see `Update a + space `__. + + If you're updating the ``displayName`` field and receive the + error message ``ALREADY_EXISTS``, try a different display name.. + An existing space within the Google Workspace organization might + already use this display name. + + Requires `user + authentication `__. + + .. 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.apps import chat_v1 + + def sample_update_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UpdateSpaceRequest( + ) + + # Make the request + response = client.update_space(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.UpdateSpaceRequest, dict]): + The request object. A request to update a single space. + space (google.apps.chat_v1.types.Space): + Required. Space with fields to be updated. + ``Space.name`` must be populated in the form of + ``spaces/{space}``. Only fields specified by + ``update_mask`` are updated. + + This corresponds to the ``space`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The updated field paths, comma separated if + there are multiple. + + Currently supported field paths: + + - ``display_name`` (Only supports changing the display + name of a space with the ``SPACE`` type, or when also + including the ``space_type`` mask to change a + ``GROUP_CHAT`` space type to ``SPACE``. Trying to + update the display name of a ``GROUP_CHAT`` or a + ``DIRECT_MESSAGE`` space results in an invalid + argument error. If you receive the error message + ``ALREADY_EXISTS`` when updating the ``displayName``, + try a different ``displayName``. An existing space + within the Google Workspace organization might + already use this display name.) + + - ``space_type`` (Only supports changing a + ``GROUP_CHAT`` space type to ``SPACE``. Include + ``display_name`` together with ``space_type`` in the + update mask and ensure that the specified space has a + non-empty display name and the ``SPACE`` space type. + Including the ``space_type`` mask and the ``SPACE`` + type in the specified space when updating the display + name is optional if the existing space already has + the ``SPACE`` type. Trying to update the space type + in other ways results in an invalid argument error). + + - ``space_details`` + + - ``space_history_state`` (Supports `turning history on + or off for the + space `__ + if `the organization allows users to change their + history + setting `__. + Warning: mutually exclusive with all other field + paths.) + + - Developer Preview: ``access_settings.audience`` + (Supports changing the `access + setting `__ + of a space. If no audience is specified in the access + setting, the space's access setting is updated to + restricted. Warning: mutually exclusive with all + other field paths.) + + 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.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # 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([space, 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a gc_space.UpdateSpaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gc_space.UpdateSpaceRequest): + request = gc_space.UpdateSpaceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if space is not None: + request.space = space + 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_space] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("space.name", request.space.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 delete_space( + self, + request: Optional[Union[space.DeleteSpaceRequest, 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]] = (), + ) -> None: + r"""Deletes a named space. Always performs a cascading delete, which + means that the space's child resources—like messages posted in + the space and memberships in the space—are also deleted. For an + example, see `Delete a + space `__. + Requires `user + authentication `__ + from a user who has permission to delete the space. + + .. 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.apps import chat_v1 + + def sample_delete_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteSpaceRequest( + name="name_value", + ) + + # Make the request + client.delete_space(request=request) + + Args: + request (Union[google.apps.chat_v1.types.DeleteSpaceRequest, dict]): + The request object. Request for deleting a space. + name (str): + Required. Resource name of the space to delete. + + Format: ``spaces/{space}`` + + 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. + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a space.DeleteSpaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, space.DeleteSpaceRequest): + request = space.DeleteSpaceRequest(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_space] + + # 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def complete_import_space( + self, + request: Optional[Union[space.CompleteImportSpaceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.CompleteImportSpaceResponse: + r"""Completes the `import + process `__ + for the specified space and makes it visible to users. Requires + app authentication and domain-wide delegation. For more + information, see `Authorize Google Chat apps to import + data `__. + + .. 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.apps import chat_v1 + + def sample_complete_import_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CompleteImportSpaceRequest( + name="name_value", + ) + + # Make the request + response = client.complete_import_space(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.CompleteImportSpaceRequest, dict]): + The request object. Request message for completing the + import process for a space. + 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.apps.chat_v1.types.CompleteImportSpaceResponse: + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a space.CompleteImportSpaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, space.CompleteImportSpaceRequest): + request = space.CompleteImportSpaceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.complete_import_space] + + # 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 find_direct_message( + self, + request: Optional[Union[space.FindDirectMessageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.Space: + r"""Returns the existing direct message with the specified user. If + no direct message space is found, returns a ``404 NOT_FOUND`` + error. For an example, see `Find a direct + message `__. + + With `user + authentication `__, + returns the direct message space between the specified user and + the authenticated user. + + With `app + authentication `__, + returns the direct message space between the specified user and + the calling Chat app. + + Requires `user + authentication `__ + or `app + authentication `__. + + .. 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.apps import chat_v1 + + def sample_find_direct_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.FindDirectMessageRequest( + name="name_value", + ) + + # Make the request + response = client.find_direct_message(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.FindDirectMessageRequest, dict]): + The request object. A request to get direct message space + based on the user resource. + 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.apps.chat_v1.types.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a space.FindDirectMessageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, space.FindDirectMessageRequest): + request = space.FindDirectMessageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.find_direct_message] + + # 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 create_membership( + self, + request: Optional[Union[gc_membership.CreateMembershipRequest, dict]] = None, + *, + parent: Optional[str] = None, + membership: Optional[gc_membership.Membership] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_membership.Membership: + r"""Creates a human membership or app membership for the calling + app. Creating memberships for other apps isn't supported. For an + example, see `Create a + membership `__. + When creating a membership, if the specified member has their + auto-accept policy turned off, then they're invited, and must + accept the space invitation before joining. Otherwise, creating + a membership adds the member directly to the specified space. + Requires `user + authentication `__. + + To specify the member to add, set the ``membership.member.name`` + in the ``CreateMembershipRequest``: + + - To add the calling app to a space or a direct message between + two human users, use ``users/app``. Unable to add other apps + to the space. + + - To add a human user, use ``users/{user}``, where ``{user}`` + can be the email address for the user. For users in the same + Workspace organization ``{user}`` can also be the ``id`` for + the person from the People API, or the ``id`` for the user in + the Directory API. For example, if the People API Person + profile ID for ``user@example.com`` is ``123456789``, you can + add the user to the space by setting the + ``membership.member.name`` to ``users/user@example.com`` or + ``users/123456789``. + + .. 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.apps import chat_v1 + + def sample_create_membership(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CreateMembershipRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.CreateMembershipRequest, dict]): + The request object. + parent (str): + Required. The resource name of the + space for which to create the + membership. + + Format: spaces/{space} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + membership (google.apps.chat_v1.types.Membership): + Required. The membership relation to create. The + ``memberType`` field must contain a user with the + ``user.name`` and ``user.type`` fields populated. The + server will assign a resource name and overwrite + anything specified. When a Chat app creates a membership + relation for a human user, it must use the + ``chat.memberships`` scope, set ``user.type`` to + ``HUMAN``, and set ``user.name`` with format + ``users/{user}``, where ``{user}`` can be the email + address for the user. For users in the same Workspace + organization ``{user}`` can also be the ``id`` of the + `person `__ + from the People API, or the ``id`` for the user in the + Directory API. For example, if the People API Person + profile ID for ``user@example.com`` is ``123456789``, + you can add the user to the space by setting the + ``membership.member.name`` to ``users/user@example.com`` + or ``users/123456789``. When a Chat app creates a + membership relation for itself, it must use the + ``chat.memberships.app`` scope, set ``user.type`` to + ``BOT``, and set ``user.name`` to ``users/app``. + + This corresponds to the ``membership`` 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.apps.chat_v1.types.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + # 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, membership]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a gc_membership.CreateMembershipRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gc_membership.CreateMembershipRequest): + request = gc_membership.CreateMembershipRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if membership is not None: + request.membership = membership + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_membership] + + # 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 delete_membership( + self, + request: Optional[Union[membership.DeleteMembershipRequest, 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]] = (), + ) -> membership.Membership: + r"""Deletes a membership. For an example, see `Delete a + membership `__. + + Requires `user + authentication `__. + + .. 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.apps import chat_v1 + + def sample_delete_membership(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMembershipRequest( + name="name_value", + ) + + # Make the request + response = client.delete_membership(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.DeleteMembershipRequest, dict]): + The request object. + name (str): + Required. Resource name of the membership to delete. + Chat apps can delete human users' or their own + memberships. Chat apps can't delete other apps' + memberships. + + When deleting a human membership, requires the + ``chat.memberships`` scope and + ``spaces/{space}/members/{member}`` format. You can use + the email as an alias for ``{member}``. For example, + ``spaces/{space}/members/example@gmail.com`` where + ``example@gmail.com`` is the email of the Google Chat + user. + + When deleting an app membership, requires the + ``chat.memberships.app`` scope and + ``spaces/{space}/members/app`` format. + + Format: ``spaces/{space}/members/{member}`` or + ``spaces/{space}/members/app``. + + 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.apps.chat_v1.types.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a membership.DeleteMembershipRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, membership.DeleteMembershipRequest): + request = membership.DeleteMembershipRequest(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_membership] + + # 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 create_reaction( + self, + request: Optional[Union[gc_reaction.CreateReactionRequest, dict]] = None, + *, + parent: Optional[str] = None, + reaction: Optional[gc_reaction.Reaction] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_reaction.Reaction: + r"""Creates a reaction and adds it to a message. For an example, see + `Create a + reaction `__. + Requires `user + authentication `__. + Only unicode emoji are supported. + + .. 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.apps import chat_v1 + + def sample_create_reaction(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CreateReactionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_reaction(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.apps.chat_v1.types.CreateReactionRequest, dict]): + The request object. Creates a reaction to a message. + parent (str): + Required. The message where the reaction is created. + + Format: ``spaces/{space}/messages/{message}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reaction (google.apps.chat_v1.types.Reaction): + Required. The reaction to create. + This corresponds to the ``reaction`` 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.apps.chat_v1.types.Reaction: + A reaction to a message. + """ + # 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, reaction]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a gc_reaction.CreateReactionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gc_reaction.CreateReactionRequest): + request = gc_reaction.CreateReactionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if reaction is not None: + request.reaction = reaction + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_reaction] + + # 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 list_reactions( + self, + request: Optional[Union[reaction.ListReactionsRequest, 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.ListReactionsPager: + r"""Lists reactions to a message. For an example, see `List + reactions `__. + Requires `user + authentication `__. + + .. 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.apps import chat_v1 + + def sample_list_reactions(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListReactionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_reactions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.apps.chat_v1.types.ListReactionsRequest, dict]): + The request object. Lists reactions to a message. + parent (str): + Required. The message users reacted to. + + Format: ``spaces/{space}/messages/{message}`` + + 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.apps.chat_v1.services.chat_service.pagers.ListReactionsPager: + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a reaction.ListReactionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, reaction.ListReactionsRequest): + request = reaction.ListReactionsRequest(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_reactions] + + # 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.ListReactionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_reaction( + self, + request: Optional[Union[reaction.DeleteReactionRequest, 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]] = (), + ) -> None: + r"""Deletes a reaction to a message. For an example, see `Delete a + reaction `__. + Requires `user + authentication `__. + + .. 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.apps import chat_v1 + + def sample_delete_reaction(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteReactionRequest( + name="name_value", + ) + + # Make the request + client.delete_reaction(request=request) + + Args: + request (Union[google.apps.chat_v1.types.DeleteReactionRequest, dict]): + The request object. Deletes a reaction to a message. + name (str): + Required. Name of the reaction to delete. + + Format: + ``spaces/{space}/messages/{message}/reactions/{reaction}`` + + 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. + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a reaction.DeleteReactionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, reaction.DeleteReactionRequest): + request = reaction.DeleteReactionRequest(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_reaction] + + # 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def __enter__(self) -> "ChatServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("ChatServiceClient",) diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/pagers.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/pagers.py new file mode 100644 index 000000000000..d2230bc04e65 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/pagers.py @@ -0,0 +1,539 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.apps.chat_v1.types import membership, message, reaction, space + + +class ListMessagesPager: + """A pager for iterating through ``list_messages`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListMessagesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``messages`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMessages`` requests and continue to iterate + through the ``messages`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListMessagesResponse` + 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[..., message.ListMessagesResponse], + request: message.ListMessagesRequest, + response: message.ListMessagesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.chat_v1.types.ListMessagesRequest): + The initial request object. + response (google.apps.chat_v1.types.ListMessagesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = message.ListMessagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[message.ListMessagesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[message.Message]: + for page in self.pages: + yield from page.messages + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMessagesAsyncPager: + """A pager for iterating through ``list_messages`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListMessagesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``messages`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMessages`` requests and continue to iterate + through the ``messages`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListMessagesResponse` + 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[message.ListMessagesResponse]], + request: message.ListMessagesRequest, + response: message.ListMessagesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.chat_v1.types.ListMessagesRequest): + The initial request object. + response (google.apps.chat_v1.types.ListMessagesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = message.ListMessagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[message.ListMessagesResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[message.Message]: + async def async_generator(): + async for page in self.pages: + for response in page.messages: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMembershipsPager: + """A pager for iterating through ``list_memberships`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListMembershipsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``memberships`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMemberships`` requests and continue to iterate + through the ``memberships`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListMembershipsResponse` + 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[..., membership.ListMembershipsResponse], + request: membership.ListMembershipsRequest, + response: membership.ListMembershipsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.chat_v1.types.ListMembershipsRequest): + The initial request object. + response (google.apps.chat_v1.types.ListMembershipsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = membership.ListMembershipsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[membership.ListMembershipsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[membership.Membership]: + for page in self.pages: + yield from page.memberships + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMembershipsAsyncPager: + """A pager for iterating through ``list_memberships`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListMembershipsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``memberships`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMemberships`` requests and continue to iterate + through the ``memberships`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListMembershipsResponse` + 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[membership.ListMembershipsResponse]], + request: membership.ListMembershipsRequest, + response: membership.ListMembershipsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.chat_v1.types.ListMembershipsRequest): + The initial request object. + response (google.apps.chat_v1.types.ListMembershipsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = membership.ListMembershipsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[membership.ListMembershipsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[membership.Membership]: + async def async_generator(): + async for page in self.pages: + for response in page.memberships: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSpacesPager: + """A pager for iterating through ``list_spaces`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListSpacesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``spaces`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSpaces`` requests and continue to iterate + through the ``spaces`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListSpacesResponse` + 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[..., space.ListSpacesResponse], + request: space.ListSpacesRequest, + response: space.ListSpacesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.chat_v1.types.ListSpacesRequest): + The initial request object. + response (google.apps.chat_v1.types.ListSpacesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = space.ListSpacesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[space.ListSpacesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[space.Space]: + for page in self.pages: + yield from page.spaces + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSpacesAsyncPager: + """A pager for iterating through ``list_spaces`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListSpacesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``spaces`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSpaces`` requests and continue to iterate + through the ``spaces`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListSpacesResponse` + 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[space.ListSpacesResponse]], + request: space.ListSpacesRequest, + response: space.ListSpacesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.chat_v1.types.ListSpacesRequest): + The initial request object. + response (google.apps.chat_v1.types.ListSpacesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = space.ListSpacesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[space.ListSpacesResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[space.Space]: + async def async_generator(): + async for page in self.pages: + for response in page.spaces: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListReactionsPager: + """A pager for iterating through ``list_reactions`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListReactionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``reactions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListReactions`` requests and continue to iterate + through the ``reactions`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListReactionsResponse` + 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[..., reaction.ListReactionsResponse], + request: reaction.ListReactionsRequest, + response: reaction.ListReactionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.chat_v1.types.ListReactionsRequest): + The initial request object. + response (google.apps.chat_v1.types.ListReactionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = reaction.ListReactionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[reaction.ListReactionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[reaction.Reaction]: + for page in self.pages: + yield from page.reactions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListReactionsAsyncPager: + """A pager for iterating through ``list_reactions`` requests. + + This class thinly wraps an initial + :class:`google.apps.chat_v1.types.ListReactionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``reactions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListReactions`` requests and continue to iterate + through the ``reactions`` field on the + corresponding responses. + + All the usual :class:`google.apps.chat_v1.types.ListReactionsResponse` + 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[reaction.ListReactionsResponse]], + request: reaction.ListReactionsRequest, + response: reaction.ListReactionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.apps.chat_v1.types.ListReactionsRequest): + The initial request object. + response (google.apps.chat_v1.types.ListReactionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = reaction.ListReactionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[reaction.ListReactionsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[reaction.Reaction]: + async def async_generator(): + async for page in self.pages: + for response in page.reactions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/__init__.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/__init__.py new file mode 100644 index 000000000000..5028f6913d6c --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ChatServiceTransport +from .grpc import ChatServiceGrpcTransport +from .grpc_asyncio import ChatServiceGrpcAsyncIOTransport +from .rest import ChatServiceRestInterceptor, ChatServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ChatServiceTransport]] +_transport_registry["grpc"] = ChatServiceGrpcTransport +_transport_registry["grpc_asyncio"] = ChatServiceGrpcAsyncIOTransport +_transport_registry["rest"] = ChatServiceRestTransport + +__all__ = ( + "ChatServiceTransport", + "ChatServiceGrpcTransport", + "ChatServiceGrpcAsyncIOTransport", + "ChatServiceRestTransport", + "ChatServiceRestInterceptor", +) diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/base.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/base.py new file mode 100644 index 000000000000..14ec828a5fa7 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/base.py @@ -0,0 +1,679 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +from google.apps.chat_v1 import gapic_version as package_version +from google.apps.chat_v1.types import attachment +from google.apps.chat_v1.types import membership +from google.apps.chat_v1.types import membership as gc_membership +from google.apps.chat_v1.types import message +from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import space +from google.apps.chat_v1.types import space as gc_space +from google.apps.chat_v1.types import space_setup + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class ChatServiceTransport(abc.ABC): + """Abstract transport class for ChatService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/chat.bot", + "https://www.googleapis.com/auth/chat.delete", + "https://www.googleapis.com/auth/chat.import", + "https://www.googleapis.com/auth/chat.memberships", + "https://www.googleapis.com/auth/chat.memberships.app", + "https://www.googleapis.com/auth/chat.memberships.readonly", + "https://www.googleapis.com/auth/chat.messages", + "https://www.googleapis.com/auth/chat.messages.create", + "https://www.googleapis.com/auth/chat.messages.reactions", + "https://www.googleapis.com/auth/chat.messages.reactions.create", + "https://www.googleapis.com/auth/chat.messages.reactions.readonly", + "https://www.googleapis.com/auth/chat.messages.readonly", + "https://www.googleapis.com/auth/chat.spaces", + "https://www.googleapis.com/auth/chat.spaces.create", + "https://www.googleapis.com/auth/chat.spaces.readonly", + ) + + DEFAULT_HOST: str = "chat.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'chat.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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_message: gapic_v1.method.wrap_method( + self.create_message, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_messages: gapic_v1.method.wrap_method( + self.list_messages, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_memberships: gapic_v1.method.wrap_method( + self.list_memberships, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_membership: gapic_v1.method.wrap_method( + self.get_membership, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_message: gapic_v1.method.wrap_method( + self.get_message, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.update_message: gapic_v1.method.wrap_method( + self.update_message, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_message: gapic_v1.method.wrap_method( + self.delete_message, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_attachment: gapic_v1.method.wrap_method( + self.get_attachment, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.upload_attachment: gapic_v1.method.wrap_method( + self.upload_attachment, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_spaces: gapic_v1.method.wrap_method( + self.list_spaces, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.get_space: gapic_v1.method.wrap_method( + self.get_space, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_space: gapic_v1.method.wrap_method( + self.create_space, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.set_up_space: gapic_v1.method.wrap_method( + self.set_up_space, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.update_space: gapic_v1.method.wrap_method( + self.update_space, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_space: gapic_v1.method.wrap_method( + self.delete_space, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.complete_import_space: gapic_v1.method.wrap_method( + self.complete_import_space, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.find_direct_message: gapic_v1.method.wrap_method( + self.find_direct_message, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_membership: gapic_v1.method.wrap_method( + self.create_membership, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_membership: gapic_v1.method.wrap_method( + self.delete_membership, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.create_reaction: gapic_v1.method.wrap_method( + self.create_reaction, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.list_reactions: gapic_v1.method.wrap_method( + self.list_reactions, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.delete_reaction: gapic_v1.method.wrap_method( + self.delete_reaction, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_message( + self, + ) -> Callable[ + [gc_message.CreateMessageRequest], + Union[gc_message.Message, Awaitable[gc_message.Message]], + ]: + raise NotImplementedError() + + @property + def list_messages( + self, + ) -> Callable[ + [message.ListMessagesRequest], + Union[message.ListMessagesResponse, Awaitable[message.ListMessagesResponse]], + ]: + raise NotImplementedError() + + @property + def list_memberships( + self, + ) -> Callable[ + [membership.ListMembershipsRequest], + Union[ + membership.ListMembershipsResponse, + Awaitable[membership.ListMembershipsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_membership( + self, + ) -> Callable[ + [membership.GetMembershipRequest], + Union[membership.Membership, Awaitable[membership.Membership]], + ]: + raise NotImplementedError() + + @property + def get_message( + self, + ) -> Callable[ + [message.GetMessageRequest], Union[message.Message, Awaitable[message.Message]] + ]: + raise NotImplementedError() + + @property + def update_message( + self, + ) -> Callable[ + [gc_message.UpdateMessageRequest], + Union[gc_message.Message, Awaitable[gc_message.Message]], + ]: + raise NotImplementedError() + + @property + def delete_message( + self, + ) -> Callable[ + [message.DeleteMessageRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def get_attachment( + self, + ) -> Callable[ + [attachment.GetAttachmentRequest], + Union[attachment.Attachment, Awaitable[attachment.Attachment]], + ]: + raise NotImplementedError() + + @property + def upload_attachment( + self, + ) -> Callable[ + [attachment.UploadAttachmentRequest], + Union[ + attachment.UploadAttachmentResponse, + Awaitable[attachment.UploadAttachmentResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_spaces( + self, + ) -> Callable[ + [space.ListSpacesRequest], + Union[space.ListSpacesResponse, Awaitable[space.ListSpacesResponse]], + ]: + raise NotImplementedError() + + @property + def get_space( + self, + ) -> Callable[[space.GetSpaceRequest], Union[space.Space, Awaitable[space.Space]]]: + raise NotImplementedError() + + @property + def create_space( + self, + ) -> Callable[ + [gc_space.CreateSpaceRequest], Union[gc_space.Space, Awaitable[gc_space.Space]] + ]: + raise NotImplementedError() + + @property + def set_up_space( + self, + ) -> Callable[ + [space_setup.SetUpSpaceRequest], Union[space.Space, Awaitable[space.Space]] + ]: + raise NotImplementedError() + + @property + def update_space( + self, + ) -> Callable[ + [gc_space.UpdateSpaceRequest], Union[gc_space.Space, Awaitable[gc_space.Space]] + ]: + raise NotImplementedError() + + @property + def delete_space( + self, + ) -> Callable[ + [space.DeleteSpaceRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] + ]: + raise NotImplementedError() + + @property + def complete_import_space( + self, + ) -> Callable[ + [space.CompleteImportSpaceRequest], + Union[ + space.CompleteImportSpaceResponse, + Awaitable[space.CompleteImportSpaceResponse], + ], + ]: + raise NotImplementedError() + + @property + def find_direct_message( + self, + ) -> Callable[ + [space.FindDirectMessageRequest], Union[space.Space, Awaitable[space.Space]] + ]: + raise NotImplementedError() + + @property + def create_membership( + self, + ) -> Callable[ + [gc_membership.CreateMembershipRequest], + Union[gc_membership.Membership, Awaitable[gc_membership.Membership]], + ]: + raise NotImplementedError() + + @property + def delete_membership( + self, + ) -> Callable[ + [membership.DeleteMembershipRequest], + Union[membership.Membership, Awaitable[membership.Membership]], + ]: + raise NotImplementedError() + + @property + def create_reaction( + self, + ) -> Callable[ + [gc_reaction.CreateReactionRequest], + Union[gc_reaction.Reaction, Awaitable[gc_reaction.Reaction]], + ]: + raise NotImplementedError() + + @property + def list_reactions( + self, + ) -> Callable[ + [reaction.ListReactionsRequest], + Union[ + reaction.ListReactionsResponse, Awaitable[reaction.ListReactionsResponse] + ], + ]: + raise NotImplementedError() + + @property + def delete_reaction( + self, + ) -> Callable[ + [reaction.DeleteReactionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("ChatServiceTransport",) diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py new file mode 100644 index 000000000000..4241c93035c0 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py @@ -0,0 +1,1057 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf import empty_pb2 # type: ignore +import grpc # type: ignore + +from google.apps.chat_v1.types import attachment +from google.apps.chat_v1.types import membership +from google.apps.chat_v1.types import membership as gc_membership +from google.apps.chat_v1.types import message +from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import space +from google.apps.chat_v1.types import space as gc_space +from google.apps.chat_v1.types import space_setup + +from .base import DEFAULT_CLIENT_INFO, ChatServiceTransport + + +class ChatServiceGrpcTransport(ChatServiceTransport): + """gRPC backend transport for ChatService. + + Enables developers to build Chat apps and + integrations on Google Chat Platform. + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "chat.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'chat.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. + This argument is ignored if ``channel`` is provided. + 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. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "chat.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def create_message( + self, + ) -> Callable[[gc_message.CreateMessageRequest], gc_message.Message]: + r"""Return a callable for the create message method over gRPC. + + Creates a message in a Google Chat space. For an example, see + `Create a + message `__. + + Calling this method requires + `authentication `__ + and supports the following authentication types: + + - For text messages, user authentication or app authentication + are supported. + - For card messages, only app authentication is supported. + (Only Chat apps can create card messages.) + + Returns: + Callable[[~.CreateMessageRequest], + ~.Message]: + 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" not in self._stubs: + self._stubs["create_message"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/CreateMessage", + request_serializer=gc_message.CreateMessageRequest.serialize, + response_deserializer=gc_message.Message.deserialize, + ) + return self._stubs["create_message"] + + @property + def list_messages( + self, + ) -> Callable[[message.ListMessagesRequest], message.ListMessagesResponse]: + r"""Return a callable for the list messages method over gRPC. + + Lists messages in a space that the caller is a member of, + including messages from blocked members and spaces. For an + example, see `List + messages `__. Requires `user + authentication `__. + + Returns: + Callable[[~.ListMessagesRequest], + ~.ListMessagesResponse]: + 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_messages" not in self._stubs: + self._stubs["list_messages"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/ListMessages", + request_serializer=message.ListMessagesRequest.serialize, + response_deserializer=message.ListMessagesResponse.deserialize, + ) + return self._stubs["list_messages"] + + @property + def list_memberships( + self, + ) -> Callable[ + [membership.ListMembershipsRequest], membership.ListMembershipsResponse + ]: + r"""Return a callable for the list memberships method over gRPC. + + Lists memberships in a space. For an example, see `List + memberships `__. + Listing memberships with `app + authentication `__ + lists memberships in spaces that the Chat app has access to, but + excludes Chat app memberships, including its own. Listing + memberships with `User + authentication `__ + lists memberships in spaces that the authenticated user has + access to. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Returns: + Callable[[~.ListMembershipsRequest], + ~.ListMembershipsResponse]: + 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_memberships" not in self._stubs: + self._stubs["list_memberships"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/ListMemberships", + request_serializer=membership.ListMembershipsRequest.serialize, + response_deserializer=membership.ListMembershipsResponse.deserialize, + ) + return self._stubs["list_memberships"] + + @property + def get_membership( + self, + ) -> Callable[[membership.GetMembershipRequest], membership.Membership]: + r"""Return a callable for the get membership method over gRPC. + + Returns details about a membership. For an example, see `Get a + membership `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Returns: + Callable[[~.GetMembershipRequest], + ~.Membership]: + 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_membership" not in self._stubs: + self._stubs["get_membership"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/GetMembership", + request_serializer=membership.GetMembershipRequest.serialize, + response_deserializer=membership.Membership.deserialize, + ) + return self._stubs["get_membership"] + + @property + def get_message(self) -> Callable[[message.GetMessageRequest], message.Message]: + r"""Return a callable for the get message method over gRPC. + + Returns details about a message. For an example, see `Read a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Note: Might return a message from a blocked member or space. + + Returns: + Callable[[~.GetMessageRequest], + ~.Message]: + 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" not in self._stubs: + self._stubs["get_message"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/GetMessage", + request_serializer=message.GetMessageRequest.serialize, + response_deserializer=message.Message.deserialize, + ) + return self._stubs["get_message"] + + @property + def update_message( + self, + ) -> Callable[[gc_message.UpdateMessageRequest], gc_message.Message]: + r"""Return a callable for the update message method over gRPC. + + Updates a message. There's a difference between the ``patch`` + and ``update`` methods. The ``patch`` method uses a ``patch`` + request while the ``update`` method uses a ``put`` request. We + recommend using the ``patch`` method. For an example, see + `Update a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + When using app authentication, requests can only update messages + created by the calling Chat app. + + Returns: + Callable[[~.UpdateMessageRequest], + ~.Message]: + 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" not in self._stubs: + self._stubs["update_message"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/UpdateMessage", + request_serializer=gc_message.UpdateMessageRequest.serialize, + response_deserializer=gc_message.Message.deserialize, + ) + return self._stubs["update_message"] + + @property + def delete_message( + self, + ) -> Callable[[message.DeleteMessageRequest], empty_pb2.Empty]: + r"""Return a callable for the delete message method over gRPC. + + Deletes a message. For an example, see `Delete a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + When using app authentication, requests can only delete messages + created by the calling Chat app. + + Returns: + Callable[[~.DeleteMessageRequest], + ~.Empty]: + 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" not in self._stubs: + self._stubs["delete_message"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/DeleteMessage", + request_serializer=message.DeleteMessageRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_message"] + + @property + def get_attachment( + self, + ) -> Callable[[attachment.GetAttachmentRequest], attachment.Attachment]: + r"""Return a callable for the get attachment method over gRPC. + + Gets the metadata of a message attachment. The attachment data + is fetched using the `media + API `__. + For an example, see `Get a message + attachment `__. + Requires `app + authentication `__. + + Returns: + Callable[[~.GetAttachmentRequest], + ~.Attachment]: + 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_attachment" not in self._stubs: + self._stubs["get_attachment"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/GetAttachment", + request_serializer=attachment.GetAttachmentRequest.serialize, + response_deserializer=attachment.Attachment.deserialize, + ) + return self._stubs["get_attachment"] + + @property + def upload_attachment( + self, + ) -> Callable[ + [attachment.UploadAttachmentRequest], attachment.UploadAttachmentResponse + ]: + r"""Return a callable for the upload attachment method over gRPC. + + Uploads an attachment. For an example, see `Upload media as a + file + attachment `__. + Requires user + `authentication `__. + + You can upload attachments up to 200 MB. Certain file types + aren't supported. For details, see `File types blocked by Google + Chat `__. + + Returns: + Callable[[~.UploadAttachmentRequest], + ~.UploadAttachmentResponse]: + 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 "upload_attachment" not in self._stubs: + self._stubs["upload_attachment"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/UploadAttachment", + request_serializer=attachment.UploadAttachmentRequest.serialize, + response_deserializer=attachment.UploadAttachmentResponse.deserialize, + ) + return self._stubs["upload_attachment"] + + @property + def list_spaces( + self, + ) -> Callable[[space.ListSpacesRequest], space.ListSpacesResponse]: + r"""Return a callable for the list spaces method over gRPC. + + Lists spaces the caller is a member of. Group chats and DMs + aren't listed until the first message is sent. For an example, + see `List + spaces `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Lists spaces visible to the caller or authenticated user. Group + chats and DMs aren't listed until the first message is sent. + + Returns: + Callable[[~.ListSpacesRequest], + ~.ListSpacesResponse]: + 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_spaces" not in self._stubs: + self._stubs["list_spaces"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/ListSpaces", + request_serializer=space.ListSpacesRequest.serialize, + response_deserializer=space.ListSpacesResponse.deserialize, + ) + return self._stubs["list_spaces"] + + @property + def get_space(self) -> Callable[[space.GetSpaceRequest], space.Space]: + r"""Return a callable for the get space method over gRPC. + + Returns details about a space. For an example, see `Get a + space `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Returns: + Callable[[~.GetSpaceRequest], + ~.Space]: + 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_space" not in self._stubs: + self._stubs["get_space"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/GetSpace", + request_serializer=space.GetSpaceRequest.serialize, + response_deserializer=space.Space.deserialize, + ) + return self._stubs["get_space"] + + @property + def create_space(self) -> Callable[[gc_space.CreateSpaceRequest], gc_space.Space]: + r"""Return a callable for the create space method over gRPC. + + Creates a named space. Spaces grouped by topics aren't + supported. For an example, see `Create a + space `__. + + If you receive the error message ``ALREADY_EXISTS`` when + creating a space, try a different ``displayName``. An existing + space within the Google Workspace organization might already use + this display name. + + Requires `user + authentication `__. + + Returns: + Callable[[~.CreateSpaceRequest], + ~.Space]: + 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_space" not in self._stubs: + self._stubs["create_space"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/CreateSpace", + request_serializer=gc_space.CreateSpaceRequest.serialize, + response_deserializer=gc_space.Space.deserialize, + ) + return self._stubs["create_space"] + + @property + def set_up_space(self) -> Callable[[space_setup.SetUpSpaceRequest], space.Space]: + r"""Return a callable for the set up space method over gRPC. + + Creates a space and adds specified users to it. The calling user + is automatically added to the space, and shouldn't be specified + as a membership in the request. For an example, see `Set up a + space `__. + + To specify the human members to add, add memberships with the + appropriate ``member.name`` in the ``SetUpSpaceRequest``. To add + a human user, use ``users/{user}``, where ``{user}`` can be the + email address for the user. For users in the same Workspace + organization ``{user}`` can also be the ``id`` for the person + from the People API, or the ``id`` for the user in the Directory + API. For example, if the People API Person profile ID for + ``user@example.com`` is ``123456789``, you can add the user to + the space by setting the ``membership.member.name`` to + ``users/user@example.com`` or ``users/123456789``. + + For a space or group chat, if the caller blocks or is blocked by + some members, then those members aren't added to the created + space. + + To create a direct message (DM) between the calling user and + another human user, specify exactly one membership to represent + the human user. If one user blocks the other, the request fails + and the DM isn't created. + + To create a DM between the calling user and the calling app, set + ``Space.singleUserBotDm`` to ``true`` and don't specify any + memberships. You can only use this method to set up a DM with + the calling app. To add the calling app as a member of a space + or an existing DM between two human users, see `create a + membership `__. + + If a DM already exists between two users, even when one user + blocks the other at the time a request is made, then the + existing DM is returned. + + Spaces with threaded replies aren't supported. If you receive + the error message ``ALREADY_EXISTS`` when setting up a space, + try a different ``displayName``. An existing space within the + Google Workspace organization might already use this display + name. + + Requires `user + authentication `__. + + Returns: + Callable[[~.SetUpSpaceRequest], + ~.Space]: + 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 "set_up_space" not in self._stubs: + self._stubs["set_up_space"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/SetUpSpace", + request_serializer=space_setup.SetUpSpaceRequest.serialize, + response_deserializer=space.Space.deserialize, + ) + return self._stubs["set_up_space"] + + @property + def update_space(self) -> Callable[[gc_space.UpdateSpaceRequest], gc_space.Space]: + r"""Return a callable for the update space method over gRPC. + + Updates a space. For an example, see `Update a + space `__. + + If you're updating the ``displayName`` field and receive the + error message ``ALREADY_EXISTS``, try a different display name.. + An existing space within the Google Workspace organization might + already use this display name. + + Requires `user + authentication `__. + + Returns: + Callable[[~.UpdateSpaceRequest], + ~.Space]: + 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_space" not in self._stubs: + self._stubs["update_space"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/UpdateSpace", + request_serializer=gc_space.UpdateSpaceRequest.serialize, + response_deserializer=gc_space.Space.deserialize, + ) + return self._stubs["update_space"] + + @property + def delete_space(self) -> Callable[[space.DeleteSpaceRequest], empty_pb2.Empty]: + r"""Return a callable for the delete space method over gRPC. + + Deletes a named space. Always performs a cascading delete, which + means that the space's child resources—like messages posted in + the space and memberships in the space—are also deleted. For an + example, see `Delete a + space `__. + Requires `user + authentication `__ + from a user who has permission to delete the space. + + Returns: + Callable[[~.DeleteSpaceRequest], + ~.Empty]: + 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_space" not in self._stubs: + self._stubs["delete_space"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/DeleteSpace", + request_serializer=space.DeleteSpaceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_space"] + + @property + def complete_import_space( + self, + ) -> Callable[ + [space.CompleteImportSpaceRequest], space.CompleteImportSpaceResponse + ]: + r"""Return a callable for the complete import space method over gRPC. + + Completes the `import + process `__ + for the specified space and makes it visible to users. Requires + app authentication and domain-wide delegation. For more + information, see `Authorize Google Chat apps to import + data `__. + + Returns: + Callable[[~.CompleteImportSpaceRequest], + ~.CompleteImportSpaceResponse]: + 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 "complete_import_space" not in self._stubs: + self._stubs["complete_import_space"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/CompleteImportSpace", + request_serializer=space.CompleteImportSpaceRequest.serialize, + response_deserializer=space.CompleteImportSpaceResponse.deserialize, + ) + return self._stubs["complete_import_space"] + + @property + def find_direct_message( + self, + ) -> Callable[[space.FindDirectMessageRequest], space.Space]: + r"""Return a callable for the find direct message method over gRPC. + + Returns the existing direct message with the specified user. If + no direct message space is found, returns a ``404 NOT_FOUND`` + error. For an example, see `Find a direct + message `__. + + With `user + authentication `__, + returns the direct message space between the specified user and + the authenticated user. + + With `app + authentication `__, + returns the direct message space between the specified user and + the calling Chat app. + + Requires `user + authentication `__ + or `app + authentication `__. + + Returns: + Callable[[~.FindDirectMessageRequest], + ~.Space]: + 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 "find_direct_message" not in self._stubs: + self._stubs["find_direct_message"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/FindDirectMessage", + request_serializer=space.FindDirectMessageRequest.serialize, + response_deserializer=space.Space.deserialize, + ) + return self._stubs["find_direct_message"] + + @property + def create_membership( + self, + ) -> Callable[[gc_membership.CreateMembershipRequest], gc_membership.Membership]: + r"""Return a callable for the create membership method over gRPC. + + Creates a human membership or app membership for the calling + app. Creating memberships for other apps isn't supported. For an + example, see `Create a + membership `__. + When creating a membership, if the specified member has their + auto-accept policy turned off, then they're invited, and must + accept the space invitation before joining. Otherwise, creating + a membership adds the member directly to the specified space. + Requires `user + authentication `__. + + To specify the member to add, set the ``membership.member.name`` + in the ``CreateMembershipRequest``: + + - To add the calling app to a space or a direct message between + two human users, use ``users/app``. Unable to add other apps + to the space. + + - To add a human user, use ``users/{user}``, where ``{user}`` + can be the email address for the user. For users in the same + Workspace organization ``{user}`` can also be the ``id`` for + the person from the People API, or the ``id`` for the user in + the Directory API. For example, if the People API Person + profile ID for ``user@example.com`` is ``123456789``, you can + add the user to the space by setting the + ``membership.member.name`` to ``users/user@example.com`` or + ``users/123456789``. + + Returns: + Callable[[~.CreateMembershipRequest], + ~.Membership]: + 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_membership" not in self._stubs: + self._stubs["create_membership"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/CreateMembership", + request_serializer=gc_membership.CreateMembershipRequest.serialize, + response_deserializer=gc_membership.Membership.deserialize, + ) + return self._stubs["create_membership"] + + @property + def delete_membership( + self, + ) -> Callable[[membership.DeleteMembershipRequest], membership.Membership]: + r"""Return a callable for the delete membership method over gRPC. + + Deletes a membership. For an example, see `Delete a + membership `__. + + Requires `user + authentication `__. + + Returns: + Callable[[~.DeleteMembershipRequest], + ~.Membership]: + 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_membership" not in self._stubs: + self._stubs["delete_membership"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/DeleteMembership", + request_serializer=membership.DeleteMembershipRequest.serialize, + response_deserializer=membership.Membership.deserialize, + ) + return self._stubs["delete_membership"] + + @property + def create_reaction( + self, + ) -> Callable[[gc_reaction.CreateReactionRequest], gc_reaction.Reaction]: + r"""Return a callable for the create reaction method over gRPC. + + Creates a reaction and adds it to a message. For an example, see + `Create a + reaction `__. + Requires `user + authentication `__. + Only unicode emoji are supported. + + Returns: + Callable[[~.CreateReactionRequest], + ~.Reaction]: + 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_reaction" not in self._stubs: + self._stubs["create_reaction"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/CreateReaction", + request_serializer=gc_reaction.CreateReactionRequest.serialize, + response_deserializer=gc_reaction.Reaction.deserialize, + ) + return self._stubs["create_reaction"] + + @property + def list_reactions( + self, + ) -> Callable[[reaction.ListReactionsRequest], reaction.ListReactionsResponse]: + r"""Return a callable for the list reactions method over gRPC. + + Lists reactions to a message. For an example, see `List + reactions `__. + Requires `user + authentication `__. + + Returns: + Callable[[~.ListReactionsRequest], + ~.ListReactionsResponse]: + 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_reactions" not in self._stubs: + self._stubs["list_reactions"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/ListReactions", + request_serializer=reaction.ListReactionsRequest.serialize, + response_deserializer=reaction.ListReactionsResponse.deserialize, + ) + return self._stubs["list_reactions"] + + @property + def delete_reaction( + self, + ) -> Callable[[reaction.DeleteReactionRequest], empty_pb2.Empty]: + r"""Return a callable for the delete reaction method over gRPC. + + Deletes a reaction to a message. For an example, see `Delete a + reaction `__. + Requires `user + authentication `__. + + Returns: + Callable[[~.DeleteReactionRequest], + ~.Empty]: + 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_reaction" not in self._stubs: + self._stubs["delete_reaction"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/DeleteReaction", + request_serializer=reaction.DeleteReactionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_reaction"] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("ChatServiceGrpcTransport",) diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..0829c42f785b --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py @@ -0,0 +1,1076 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf import empty_pb2 # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.apps.chat_v1.types import attachment +from google.apps.chat_v1.types import membership +from google.apps.chat_v1.types import membership as gc_membership +from google.apps.chat_v1.types import message +from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import space +from google.apps.chat_v1.types import space as gc_space +from google.apps.chat_v1.types import space_setup + +from .base import DEFAULT_CLIENT_INFO, ChatServiceTransport +from .grpc import ChatServiceGrpcTransport + + +class ChatServiceGrpcAsyncIOTransport(ChatServiceTransport): + """gRPC AsyncIO backend transport for ChatService. + + Enables developers to build Chat apps and + integrations on Google Chat Platform. + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "chat.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "chat.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'chat.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. + This argument is ignored if ``channel`` is provided. + 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_message( + self, + ) -> Callable[[gc_message.CreateMessageRequest], Awaitable[gc_message.Message]]: + r"""Return a callable for the create message method over gRPC. + + Creates a message in a Google Chat space. For an example, see + `Create a + message `__. + + Calling this method requires + `authentication `__ + and supports the following authentication types: + + - For text messages, user authentication or app authentication + are supported. + - For card messages, only app authentication is supported. + (Only Chat apps can create card messages.) + + Returns: + Callable[[~.CreateMessageRequest], + Awaitable[~.Message]]: + 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" not in self._stubs: + self._stubs["create_message"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/CreateMessage", + request_serializer=gc_message.CreateMessageRequest.serialize, + response_deserializer=gc_message.Message.deserialize, + ) + return self._stubs["create_message"] + + @property + def list_messages( + self, + ) -> Callable[ + [message.ListMessagesRequest], Awaitable[message.ListMessagesResponse] + ]: + r"""Return a callable for the list messages method over gRPC. + + Lists messages in a space that the caller is a member of, + including messages from blocked members and spaces. For an + example, see `List + messages `__. Requires `user + authentication `__. + + Returns: + Callable[[~.ListMessagesRequest], + Awaitable[~.ListMessagesResponse]]: + 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_messages" not in self._stubs: + self._stubs["list_messages"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/ListMessages", + request_serializer=message.ListMessagesRequest.serialize, + response_deserializer=message.ListMessagesResponse.deserialize, + ) + return self._stubs["list_messages"] + + @property + def list_memberships( + self, + ) -> Callable[ + [membership.ListMembershipsRequest], + Awaitable[membership.ListMembershipsResponse], + ]: + r"""Return a callable for the list memberships method over gRPC. + + Lists memberships in a space. For an example, see `List + memberships `__. + Listing memberships with `app + authentication `__ + lists memberships in spaces that the Chat app has access to, but + excludes Chat app memberships, including its own. Listing + memberships with `User + authentication `__ + lists memberships in spaces that the authenticated user has + access to. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Returns: + Callable[[~.ListMembershipsRequest], + Awaitable[~.ListMembershipsResponse]]: + 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_memberships" not in self._stubs: + self._stubs["list_memberships"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/ListMemberships", + request_serializer=membership.ListMembershipsRequest.serialize, + response_deserializer=membership.ListMembershipsResponse.deserialize, + ) + return self._stubs["list_memberships"] + + @property + def get_membership( + self, + ) -> Callable[[membership.GetMembershipRequest], Awaitable[membership.Membership]]: + r"""Return a callable for the get membership method over gRPC. + + Returns details about a membership. For an example, see `Get a + membership `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Returns: + Callable[[~.GetMembershipRequest], + Awaitable[~.Membership]]: + 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_membership" not in self._stubs: + self._stubs["get_membership"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/GetMembership", + request_serializer=membership.GetMembershipRequest.serialize, + response_deserializer=membership.Membership.deserialize, + ) + return self._stubs["get_membership"] + + @property + def get_message( + self, + ) -> Callable[[message.GetMessageRequest], Awaitable[message.Message]]: + r"""Return a callable for the get message method over gRPC. + + Returns details about a message. For an example, see `Read a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Note: Might return a message from a blocked member or space. + + Returns: + Callable[[~.GetMessageRequest], + Awaitable[~.Message]]: + 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" not in self._stubs: + self._stubs["get_message"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/GetMessage", + request_serializer=message.GetMessageRequest.serialize, + response_deserializer=message.Message.deserialize, + ) + return self._stubs["get_message"] + + @property + def update_message( + self, + ) -> Callable[[gc_message.UpdateMessageRequest], Awaitable[gc_message.Message]]: + r"""Return a callable for the update message method over gRPC. + + Updates a message. There's a difference between the ``patch`` + and ``update`` methods. The ``patch`` method uses a ``patch`` + request while the ``update`` method uses a ``put`` request. We + recommend using the ``patch`` method. For an example, see + `Update a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + When using app authentication, requests can only update messages + created by the calling Chat app. + + Returns: + Callable[[~.UpdateMessageRequest], + Awaitable[~.Message]]: + 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" not in self._stubs: + self._stubs["update_message"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/UpdateMessage", + request_serializer=gc_message.UpdateMessageRequest.serialize, + response_deserializer=gc_message.Message.deserialize, + ) + return self._stubs["update_message"] + + @property + def delete_message( + self, + ) -> Callable[[message.DeleteMessageRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete message method over gRPC. + + Deletes a message. For an example, see `Delete a + message `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + When using app authentication, requests can only delete messages + created by the calling Chat app. + + Returns: + Callable[[~.DeleteMessageRequest], + Awaitable[~.Empty]]: + 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" not in self._stubs: + self._stubs["delete_message"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/DeleteMessage", + request_serializer=message.DeleteMessageRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_message"] + + @property + def get_attachment( + self, + ) -> Callable[[attachment.GetAttachmentRequest], Awaitable[attachment.Attachment]]: + r"""Return a callable for the get attachment method over gRPC. + + Gets the metadata of a message attachment. The attachment data + is fetched using the `media + API `__. + For an example, see `Get a message + attachment `__. + Requires `app + authentication `__. + + Returns: + Callable[[~.GetAttachmentRequest], + Awaitable[~.Attachment]]: + 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_attachment" not in self._stubs: + self._stubs["get_attachment"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/GetAttachment", + request_serializer=attachment.GetAttachmentRequest.serialize, + response_deserializer=attachment.Attachment.deserialize, + ) + return self._stubs["get_attachment"] + + @property + def upload_attachment( + self, + ) -> Callable[ + [attachment.UploadAttachmentRequest], + Awaitable[attachment.UploadAttachmentResponse], + ]: + r"""Return a callable for the upload attachment method over gRPC. + + Uploads an attachment. For an example, see `Upload media as a + file + attachment `__. + Requires user + `authentication `__. + + You can upload attachments up to 200 MB. Certain file types + aren't supported. For details, see `File types blocked by Google + Chat `__. + + Returns: + Callable[[~.UploadAttachmentRequest], + Awaitable[~.UploadAttachmentResponse]]: + 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 "upload_attachment" not in self._stubs: + self._stubs["upload_attachment"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/UploadAttachment", + request_serializer=attachment.UploadAttachmentRequest.serialize, + response_deserializer=attachment.UploadAttachmentResponse.deserialize, + ) + return self._stubs["upload_attachment"] + + @property + def list_spaces( + self, + ) -> Callable[[space.ListSpacesRequest], Awaitable[space.ListSpacesResponse]]: + r"""Return a callable for the list spaces method over gRPC. + + Lists spaces the caller is a member of. Group chats and DMs + aren't listed until the first message is sent. For an example, + see `List + spaces `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Lists spaces visible to the caller or authenticated user. Group + chats and DMs aren't listed until the first message is sent. + + Returns: + Callable[[~.ListSpacesRequest], + Awaitable[~.ListSpacesResponse]]: + 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_spaces" not in self._stubs: + self._stubs["list_spaces"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/ListSpaces", + request_serializer=space.ListSpacesRequest.serialize, + response_deserializer=space.ListSpacesResponse.deserialize, + ) + return self._stubs["list_spaces"] + + @property + def get_space(self) -> Callable[[space.GetSpaceRequest], Awaitable[space.Space]]: + r"""Return a callable for the get space method over gRPC. + + Returns details about a space. For an example, see `Get a + space `__. + + Requires + `authentication `__. + Supports `app + authentication `__ + and `user + authentication `__. + + Returns: + Callable[[~.GetSpaceRequest], + Awaitable[~.Space]]: + 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_space" not in self._stubs: + self._stubs["get_space"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/GetSpace", + request_serializer=space.GetSpaceRequest.serialize, + response_deserializer=space.Space.deserialize, + ) + return self._stubs["get_space"] + + @property + def create_space( + self, + ) -> Callable[[gc_space.CreateSpaceRequest], Awaitable[gc_space.Space]]: + r"""Return a callable for the create space method over gRPC. + + Creates a named space. Spaces grouped by topics aren't + supported. For an example, see `Create a + space `__. + + If you receive the error message ``ALREADY_EXISTS`` when + creating a space, try a different ``displayName``. An existing + space within the Google Workspace organization might already use + this display name. + + Requires `user + authentication `__. + + Returns: + Callable[[~.CreateSpaceRequest], + Awaitable[~.Space]]: + 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_space" not in self._stubs: + self._stubs["create_space"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/CreateSpace", + request_serializer=gc_space.CreateSpaceRequest.serialize, + response_deserializer=gc_space.Space.deserialize, + ) + return self._stubs["create_space"] + + @property + def set_up_space( + self, + ) -> Callable[[space_setup.SetUpSpaceRequest], Awaitable[space.Space]]: + r"""Return a callable for the set up space method over gRPC. + + Creates a space and adds specified users to it. The calling user + is automatically added to the space, and shouldn't be specified + as a membership in the request. For an example, see `Set up a + space `__. + + To specify the human members to add, add memberships with the + appropriate ``member.name`` in the ``SetUpSpaceRequest``. To add + a human user, use ``users/{user}``, where ``{user}`` can be the + email address for the user. For users in the same Workspace + organization ``{user}`` can also be the ``id`` for the person + from the People API, or the ``id`` for the user in the Directory + API. For example, if the People API Person profile ID for + ``user@example.com`` is ``123456789``, you can add the user to + the space by setting the ``membership.member.name`` to + ``users/user@example.com`` or ``users/123456789``. + + For a space or group chat, if the caller blocks or is blocked by + some members, then those members aren't added to the created + space. + + To create a direct message (DM) between the calling user and + another human user, specify exactly one membership to represent + the human user. If one user blocks the other, the request fails + and the DM isn't created. + + To create a DM between the calling user and the calling app, set + ``Space.singleUserBotDm`` to ``true`` and don't specify any + memberships. You can only use this method to set up a DM with + the calling app. To add the calling app as a member of a space + or an existing DM between two human users, see `create a + membership `__. + + If a DM already exists between two users, even when one user + blocks the other at the time a request is made, then the + existing DM is returned. + + Spaces with threaded replies aren't supported. If you receive + the error message ``ALREADY_EXISTS`` when setting up a space, + try a different ``displayName``. An existing space within the + Google Workspace organization might already use this display + name. + + Requires `user + authentication `__. + + Returns: + Callable[[~.SetUpSpaceRequest], + Awaitable[~.Space]]: + 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 "set_up_space" not in self._stubs: + self._stubs["set_up_space"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/SetUpSpace", + request_serializer=space_setup.SetUpSpaceRequest.serialize, + response_deserializer=space.Space.deserialize, + ) + return self._stubs["set_up_space"] + + @property + def update_space( + self, + ) -> Callable[[gc_space.UpdateSpaceRequest], Awaitable[gc_space.Space]]: + r"""Return a callable for the update space method over gRPC. + + Updates a space. For an example, see `Update a + space `__. + + If you're updating the ``displayName`` field and receive the + error message ``ALREADY_EXISTS``, try a different display name.. + An existing space within the Google Workspace organization might + already use this display name. + + Requires `user + authentication `__. + + Returns: + Callable[[~.UpdateSpaceRequest], + Awaitable[~.Space]]: + 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_space" not in self._stubs: + self._stubs["update_space"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/UpdateSpace", + request_serializer=gc_space.UpdateSpaceRequest.serialize, + response_deserializer=gc_space.Space.deserialize, + ) + return self._stubs["update_space"] + + @property + def delete_space( + self, + ) -> Callable[[space.DeleteSpaceRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete space method over gRPC. + + Deletes a named space. Always performs a cascading delete, which + means that the space's child resources—like messages posted in + the space and memberships in the space—are also deleted. For an + example, see `Delete a + space `__. + Requires `user + authentication `__ + from a user who has permission to delete the space. + + Returns: + Callable[[~.DeleteSpaceRequest], + Awaitable[~.Empty]]: + 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_space" not in self._stubs: + self._stubs["delete_space"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/DeleteSpace", + request_serializer=space.DeleteSpaceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_space"] + + @property + def complete_import_space( + self, + ) -> Callable[ + [space.CompleteImportSpaceRequest], Awaitable[space.CompleteImportSpaceResponse] + ]: + r"""Return a callable for the complete import space method over gRPC. + + Completes the `import + process `__ + for the specified space and makes it visible to users. Requires + app authentication and domain-wide delegation. For more + information, see `Authorize Google Chat apps to import + data `__. + + Returns: + Callable[[~.CompleteImportSpaceRequest], + Awaitable[~.CompleteImportSpaceResponse]]: + 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 "complete_import_space" not in self._stubs: + self._stubs["complete_import_space"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/CompleteImportSpace", + request_serializer=space.CompleteImportSpaceRequest.serialize, + response_deserializer=space.CompleteImportSpaceResponse.deserialize, + ) + return self._stubs["complete_import_space"] + + @property + def find_direct_message( + self, + ) -> Callable[[space.FindDirectMessageRequest], Awaitable[space.Space]]: + r"""Return a callable for the find direct message method over gRPC. + + Returns the existing direct message with the specified user. If + no direct message space is found, returns a ``404 NOT_FOUND`` + error. For an example, see `Find a direct + message `__. + + With `user + authentication `__, + returns the direct message space between the specified user and + the authenticated user. + + With `app + authentication `__, + returns the direct message space between the specified user and + the calling Chat app. + + Requires `user + authentication `__ + or `app + authentication `__. + + Returns: + Callable[[~.FindDirectMessageRequest], + Awaitable[~.Space]]: + 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 "find_direct_message" not in self._stubs: + self._stubs["find_direct_message"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/FindDirectMessage", + request_serializer=space.FindDirectMessageRequest.serialize, + response_deserializer=space.Space.deserialize, + ) + return self._stubs["find_direct_message"] + + @property + def create_membership( + self, + ) -> Callable[ + [gc_membership.CreateMembershipRequest], Awaitable[gc_membership.Membership] + ]: + r"""Return a callable for the create membership method over gRPC. + + Creates a human membership or app membership for the calling + app. Creating memberships for other apps isn't supported. For an + example, see `Create a + membership `__. + When creating a membership, if the specified member has their + auto-accept policy turned off, then they're invited, and must + accept the space invitation before joining. Otherwise, creating + a membership adds the member directly to the specified space. + Requires `user + authentication `__. + + To specify the member to add, set the ``membership.member.name`` + in the ``CreateMembershipRequest``: + + - To add the calling app to a space or a direct message between + two human users, use ``users/app``. Unable to add other apps + to the space. + + - To add a human user, use ``users/{user}``, where ``{user}`` + can be the email address for the user. For users in the same + Workspace organization ``{user}`` can also be the ``id`` for + the person from the People API, or the ``id`` for the user in + the Directory API. For example, if the People API Person + profile ID for ``user@example.com`` is ``123456789``, you can + add the user to the space by setting the + ``membership.member.name`` to ``users/user@example.com`` or + ``users/123456789``. + + Returns: + Callable[[~.CreateMembershipRequest], + Awaitable[~.Membership]]: + 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_membership" not in self._stubs: + self._stubs["create_membership"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/CreateMembership", + request_serializer=gc_membership.CreateMembershipRequest.serialize, + response_deserializer=gc_membership.Membership.deserialize, + ) + return self._stubs["create_membership"] + + @property + def delete_membership( + self, + ) -> Callable[ + [membership.DeleteMembershipRequest], Awaitable[membership.Membership] + ]: + r"""Return a callable for the delete membership method over gRPC. + + Deletes a membership. For an example, see `Delete a + membership `__. + + Requires `user + authentication `__. + + Returns: + Callable[[~.DeleteMembershipRequest], + Awaitable[~.Membership]]: + 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_membership" not in self._stubs: + self._stubs["delete_membership"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/DeleteMembership", + request_serializer=membership.DeleteMembershipRequest.serialize, + response_deserializer=membership.Membership.deserialize, + ) + return self._stubs["delete_membership"] + + @property + def create_reaction( + self, + ) -> Callable[[gc_reaction.CreateReactionRequest], Awaitable[gc_reaction.Reaction]]: + r"""Return a callable for the create reaction method over gRPC. + + Creates a reaction and adds it to a message. For an example, see + `Create a + reaction `__. + Requires `user + authentication `__. + Only unicode emoji are supported. + + Returns: + Callable[[~.CreateReactionRequest], + Awaitable[~.Reaction]]: + 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_reaction" not in self._stubs: + self._stubs["create_reaction"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/CreateReaction", + request_serializer=gc_reaction.CreateReactionRequest.serialize, + response_deserializer=gc_reaction.Reaction.deserialize, + ) + return self._stubs["create_reaction"] + + @property + def list_reactions( + self, + ) -> Callable[ + [reaction.ListReactionsRequest], Awaitable[reaction.ListReactionsResponse] + ]: + r"""Return a callable for the list reactions method over gRPC. + + Lists reactions to a message. For an example, see `List + reactions `__. + Requires `user + authentication `__. + + Returns: + Callable[[~.ListReactionsRequest], + Awaitable[~.ListReactionsResponse]]: + 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_reactions" not in self._stubs: + self._stubs["list_reactions"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/ListReactions", + request_serializer=reaction.ListReactionsRequest.serialize, + response_deserializer=reaction.ListReactionsResponse.deserialize, + ) + return self._stubs["list_reactions"] + + @property + def delete_reaction( + self, + ) -> Callable[[reaction.DeleteReactionRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete reaction method over gRPC. + + Deletes a reaction to a message. For an example, see `Delete a + reaction `__. + Requires `user + authentication `__. + + Returns: + Callable[[~.DeleteReactionRequest], + Awaitable[~.Empty]]: + 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_reaction" not in self._stubs: + self._stubs["delete_reaction"] = self.grpc_channel.unary_unary( + "/google.chat.v1.ChatService/DeleteReaction", + request_serializer=reaction.DeleteReactionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_reaction"] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ("ChatServiceGrpcAsyncIOTransport",) diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest.py new file mode 100644 index 000000000000..524517d41fa7 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/rest.py @@ -0,0 +1,2905 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.protobuf import empty_pb2 # type: ignore + +from google.apps.chat_v1.types import attachment +from google.apps.chat_v1.types import membership +from google.apps.chat_v1.types import membership as gc_membership +from google.apps.chat_v1.types import message +from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import space +from google.apps.chat_v1.types import space as gc_space +from google.apps.chat_v1.types import space_setup + +from .base import ChatServiceTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ChatServiceRestInterceptor: + """Interceptor for ChatService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the ChatServiceRestTransport. + + .. code-block:: python + class MyCustomChatServiceInterceptor(ChatServiceRestInterceptor): + def pre_complete_import_space(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_complete_import_space(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_message(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_message(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_reaction(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_reaction(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_space(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_space(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_message(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_reaction(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_space(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_find_direct_message(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_find_direct_message(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_attachment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_attachment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_membership(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_membership(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_message(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_message(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_space(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_space(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_memberships(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_memberships(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_messages(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_messages(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_reactions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_reactions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_spaces(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_spaces(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_up_space(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_up_space(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_message(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_message(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_space(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_space(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_upload_attachment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_upload_attachment(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ChatServiceRestTransport(interceptor=MyCustomChatServiceInterceptor()) + client = ChatServiceClient(transport=transport) + + + """ + + def pre_complete_import_space( + self, + request: space.CompleteImportSpaceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[space.CompleteImportSpaceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for complete_import_space + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_complete_import_space( + self, response: space.CompleteImportSpaceResponse + ) -> space.CompleteImportSpaceResponse: + """Post-rpc interceptor for complete_import_space + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_create_membership( + self, + request: gc_membership.CreateMembershipRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gc_membership.CreateMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_create_membership( + self, response: gc_membership.Membership + ) -> gc_membership.Membership: + """Post-rpc interceptor for create_membership + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_create_message( + self, + request: gc_message.CreateMessageRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gc_message.CreateMessageRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_message + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_create_message(self, response: gc_message.Message) -> gc_message.Message: + """Post-rpc interceptor for create_message + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_create_reaction( + self, + request: gc_reaction.CreateReactionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gc_reaction.CreateReactionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_reaction + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_create_reaction( + self, response: gc_reaction.Reaction + ) -> gc_reaction.Reaction: + """Post-rpc interceptor for create_reaction + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_create_space( + self, request: gc_space.CreateSpaceRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[gc_space.CreateSpaceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_space + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_create_space(self, response: gc_space.Space) -> gc_space.Space: + """Post-rpc interceptor for create_space + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_delete_membership( + self, + request: membership.DeleteMembershipRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[membership.DeleteMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_delete_membership( + self, response: membership.Membership + ) -> membership.Membership: + """Post-rpc interceptor for delete_membership + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_delete_message( + self, request: message.DeleteMessageRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[message.DeleteMessageRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_message + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def pre_delete_reaction( + self, + request: reaction.DeleteReactionRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reaction.DeleteReactionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_reaction + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def pre_delete_space( + self, request: space.DeleteSpaceRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[space.DeleteSpaceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_space + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def pre_find_direct_message( + self, + request: space.FindDirectMessageRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[space.FindDirectMessageRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for find_direct_message + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_find_direct_message(self, response: space.Space) -> space.Space: + """Post-rpc interceptor for find_direct_message + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_get_attachment( + self, + request: attachment.GetAttachmentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[attachment.GetAttachmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_attachment + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_get_attachment( + self, response: attachment.Attachment + ) -> attachment.Attachment: + """Post-rpc interceptor for get_attachment + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_get_membership( + self, + request: membership.GetMembershipRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[membership.GetMembershipRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_get_membership( + self, response: membership.Membership + ) -> membership.Membership: + """Post-rpc interceptor for get_membership + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_get_message( + self, request: message.GetMessageRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[message.GetMessageRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_message + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_get_message(self, response: message.Message) -> message.Message: + """Post-rpc interceptor for get_message + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_get_space( + self, request: space.GetSpaceRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[space.GetSpaceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_space + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_get_space(self, response: space.Space) -> space.Space: + """Post-rpc interceptor for get_space + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_list_memberships( + self, + request: membership.ListMembershipsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[membership.ListMembershipsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_memberships + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_list_memberships( + self, response: membership.ListMembershipsResponse + ) -> membership.ListMembershipsResponse: + """Post-rpc interceptor for list_memberships + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_list_messages( + self, request: message.ListMessagesRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[message.ListMessagesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_messages + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_list_messages( + self, response: message.ListMessagesResponse + ) -> message.ListMessagesResponse: + """Post-rpc interceptor for list_messages + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_list_reactions( + self, + request: reaction.ListReactionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reaction.ListReactionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_reactions + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_list_reactions( + self, response: reaction.ListReactionsResponse + ) -> reaction.ListReactionsResponse: + """Post-rpc interceptor for list_reactions + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_list_spaces( + self, request: space.ListSpacesRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[space.ListSpacesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_spaces + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_list_spaces( + self, response: space.ListSpacesResponse + ) -> space.ListSpacesResponse: + """Post-rpc interceptor for list_spaces + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_set_up_space( + self, + request: space_setup.SetUpSpaceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[space_setup.SetUpSpaceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_up_space + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_set_up_space(self, response: space.Space) -> space.Space: + """Post-rpc interceptor for set_up_space + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_update_message( + self, + request: gc_message.UpdateMessageRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gc_message.UpdateMessageRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_message + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_update_message(self, response: gc_message.Message) -> gc_message.Message: + """Post-rpc interceptor for update_message + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_update_space( + self, request: gc_space.UpdateSpaceRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[gc_space.UpdateSpaceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_space + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_update_space(self, response: gc_space.Space) -> gc_space.Space: + """Post-rpc interceptor for update_space + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + def pre_upload_attachment( + self, + request: attachment.UploadAttachmentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[attachment.UploadAttachmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for upload_attachment + + Override in a subclass to manipulate the request or metadata + before they are sent to the ChatService server. + """ + return request, metadata + + def post_upload_attachment( + self, response: attachment.UploadAttachmentResponse + ) -> attachment.UploadAttachmentResponse: + """Post-rpc interceptor for upload_attachment + + Override in a subclass to manipulate the response + after it is returned by the ChatService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ChatServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ChatServiceRestInterceptor + + +class ChatServiceRestTransport(ChatServiceTransport): + """REST backend transport for ChatService. + + Enables developers to build Chat apps and + integrations on Google Chat Platform. + + 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 = "chat.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[ChatServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'chat.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 + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ChatServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CompleteImportSpace(ChatServiceRestStub): + def __hash__(self): + return hash("CompleteImportSpace") + + __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 + } + + def __call__( + self, + request: space.CompleteImportSpaceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.CompleteImportSpaceResponse: + r"""Call the complete import space method over HTTP. + + Args: + request (~.space.CompleteImportSpaceRequest): + The request object. Request message for completing the + import process for a space. + 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: + ~.space.CompleteImportSpaceResponse: + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=spaces/*}:completeImport", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_complete_import_space( + request, metadata + ) + pb_request = space.CompleteImportSpaceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = space.CompleteImportSpaceResponse() + pb_resp = space.CompleteImportSpaceResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_complete_import_space(resp) + return resp + + class _CreateMembership(ChatServiceRestStub): + def __hash__(self): + return hash("CreateMembership") + + __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 + } + + def __call__( + self, + request: gc_membership.CreateMembershipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_membership.Membership: + r"""Call the create membership method over HTTP. + + Args: + request (~.gc_membership.CreateMembershipRequest): + The request 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. + + Returns: + ~.gc_membership.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=spaces/*}/members", + "body": "membership", + }, + ] + request, metadata = self._interceptor.pre_create_membership( + request, metadata + ) + pb_request = gc_membership.CreateMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gc_membership.Membership() + pb_resp = gc_membership.Membership.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_membership(resp) + return resp + + class _CreateMessage(ChatServiceRestStub): + def __hash__(self): + return hash("CreateMessage") + + __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 + } + + def __call__( + self, + request: gc_message.CreateMessageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_message.Message: + r"""Call the create message method over HTTP. + + Args: + request (~.gc_message.CreateMessageRequest): + The request object. Creates a message. + 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: + ~.gc_message.Message: + A message in a Google Chat space. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=spaces/*}/messages", + "body": "message", + }, + ] + request, metadata = self._interceptor.pre_create_message(request, metadata) + pb_request = gc_message.CreateMessageRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gc_message.Message() + pb_resp = gc_message.Message.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_message(resp) + return resp + + class _CreateReaction(ChatServiceRestStub): + def __hash__(self): + return hash("CreateReaction") + + __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 + } + + def __call__( + self, + request: gc_reaction.CreateReactionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_reaction.Reaction: + r"""Call the create reaction method over HTTP. + + Args: + request (~.gc_reaction.CreateReactionRequest): + The request object. Creates a reaction to a message. + 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: + ~.gc_reaction.Reaction: + A reaction to a message. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=spaces/*/messages/*}/reactions", + "body": "reaction", + }, + ] + request, metadata = self._interceptor.pre_create_reaction(request, metadata) + pb_request = gc_reaction.CreateReactionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gc_reaction.Reaction() + pb_resp = gc_reaction.Reaction.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_reaction(resp) + return resp + + class _CreateSpace(ChatServiceRestStub): + def __hash__(self): + return hash("CreateSpace") + + __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 + } + + def __call__( + self, + request: gc_space.CreateSpaceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_space.Space: + r"""Call the create space method over HTTP. + + Args: + request (~.gc_space.CreateSpaceRequest): + The request 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. + + Returns: + ~.gc_space.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/spaces", + "body": "space", + }, + ] + request, metadata = self._interceptor.pre_create_space(request, metadata) + pb_request = gc_space.CreateSpaceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gc_space.Space() + pb_resp = gc_space.Space.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_space(resp) + return resp + + class _DeleteMembership(ChatServiceRestStub): + def __hash__(self): + return hash("DeleteMembership") + + __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 + } + + def __call__( + self, + request: membership.DeleteMembershipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.Membership: + r"""Call the delete membership method over HTTP. + + Args: + request (~.membership.DeleteMembershipRequest): + The request 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. + + Returns: + ~.membership.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=spaces/*/members/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_membership( + request, metadata + ) + pb_request = membership.DeleteMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = membership.Membership() + pb_resp = membership.Membership.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_membership(resp) + return resp + + class _DeleteMessage(ChatServiceRestStub): + def __hash__(self): + return hash("DeleteMessage") + + __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 + } + + def __call__( + self, + request: message.DeleteMessageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete message method over HTTP. + + Args: + request (~.message.DeleteMessageRequest): + The request 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=spaces/*/messages/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_message(request, metadata) + pb_request = message.DeleteMessageRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteReaction(ChatServiceRestStub): + def __hash__(self): + return hash("DeleteReaction") + + __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 + } + + def __call__( + self, + request: reaction.DeleteReactionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete reaction method over HTTP. + + Args: + request (~.reaction.DeleteReactionRequest): + The request object. Deletes a reaction to a message. + 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=spaces/*/messages/*/reactions/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_reaction(request, metadata) + pb_request = reaction.DeleteReactionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteSpace(ChatServiceRestStub): + def __hash__(self): + return hash("DeleteSpace") + + __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 + } + + def __call__( + self, + request: space.DeleteSpaceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete space method over HTTP. + + Args: + request (~.space.DeleteSpaceRequest): + The request object. Request for deleting a space. + 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=spaces/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_space(request, metadata) + pb_request = space.DeleteSpaceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _FindDirectMessage(ChatServiceRestStub): + def __hash__(self): + return hash("FindDirectMessage") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "name": "", + } + + @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 + } + + def __call__( + self, + request: space.FindDirectMessageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.Space: + r"""Call the find direct message method over HTTP. + + Args: + request (~.space.FindDirectMessageRequest): + The request object. A request to get direct message space + based on the user resource. + 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: + ~.space.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/spaces:findDirectMessage", + }, + ] + request, metadata = self._interceptor.pre_find_direct_message( + request, metadata + ) + pb_request = space.FindDirectMessageRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = space.Space() + pb_resp = space.Space.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_find_direct_message(resp) + return resp + + class _GetAttachment(ChatServiceRestStub): + def __hash__(self): + return hash("GetAttachment") + + __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 + } + + def __call__( + self, + request: attachment.GetAttachmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> attachment.Attachment: + r"""Call the get attachment method over HTTP. + + Args: + request (~.attachment.GetAttachmentRequest): + The request 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. + + Returns: + ~.attachment.Attachment: + An attachment in Google Chat. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=spaces/*/messages/*/attachments/*}", + }, + ] + request, metadata = self._interceptor.pre_get_attachment(request, metadata) + pb_request = attachment.GetAttachmentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = attachment.Attachment() + pb_resp = attachment.Attachment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_attachment(resp) + return resp + + class _GetMembership(ChatServiceRestStub): + def __hash__(self): + return hash("GetMembership") + + __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 + } + + def __call__( + self, + request: membership.GetMembershipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.Membership: + r"""Call the get membership method over HTTP. + + Args: + request (~.membership.GetMembershipRequest): + The request 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. + + Returns: + ~.membership.Membership: + Represents a membership relation in + Google Chat, such as whether a user or + Chat app is invited to, part of, or + absent from a space. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=spaces/*/members/*}", + }, + ] + request, metadata = self._interceptor.pre_get_membership(request, metadata) + pb_request = membership.GetMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = membership.Membership() + pb_resp = membership.Membership.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_membership(resp) + return resp + + class _GetMessage(ChatServiceRestStub): + def __hash__(self): + return hash("GetMessage") + + __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 + } + + def __call__( + self, + request: message.GetMessageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> message.Message: + r"""Call the get message method over HTTP. + + Args: + request (~.message.GetMessageRequest): + The request 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. + + Returns: + ~.message.Message: + A message in a Google Chat space. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=spaces/*/messages/*}", + }, + ] + request, metadata = self._interceptor.pre_get_message(request, metadata) + pb_request = message.GetMessageRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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.Message() + pb_resp = message.Message.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_message(resp) + return resp + + class _GetSpace(ChatServiceRestStub): + def __hash__(self): + return hash("GetSpace") + + __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 + } + + def __call__( + self, + request: space.GetSpaceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.Space: + r"""Call the get space method over HTTP. + + Args: + request (~.space.GetSpaceRequest): + The request object. A request to return a single space. + 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: + ~.space.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=spaces/*}", + }, + ] + request, metadata = self._interceptor.pre_get_space(request, metadata) + pb_request = space.GetSpaceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = space.Space() + pb_resp = space.Space.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_space(resp) + return resp + + class _ListMemberships(ChatServiceRestStub): + def __hash__(self): + return hash("ListMemberships") + + __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 + } + + def __call__( + self, + request: membership.ListMembershipsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> membership.ListMembershipsResponse: + r"""Call the list memberships method over HTTP. + + Args: + request (~.membership.ListMembershipsRequest): + The request 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. + + Returns: + ~.membership.ListMembershipsResponse: + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=spaces/*}/members", + }, + ] + request, metadata = self._interceptor.pre_list_memberships( + request, metadata + ) + pb_request = membership.ListMembershipsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = membership.ListMembershipsResponse() + pb_resp = membership.ListMembershipsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_memberships(resp) + return resp + + class _ListMessages(ChatServiceRestStub): + def __hash__(self): + return hash("ListMessages") + + __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 + } + + def __call__( + self, + request: message.ListMessagesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> message.ListMessagesResponse: + r"""Call the list messages method over HTTP. + + Args: + request (~.message.ListMessagesRequest): + The request object. Lists messages in the specified + space, that the user is a member of. + 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: + ~.message.ListMessagesResponse: + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=spaces/*}/messages", + }, + ] + request, metadata = self._interceptor.pre_list_messages(request, metadata) + pb_request = message.ListMessagesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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.ListMessagesResponse() + pb_resp = message.ListMessagesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_messages(resp) + return resp + + class _ListReactions(ChatServiceRestStub): + def __hash__(self): + return hash("ListReactions") + + __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 + } + + def __call__( + self, + request: reaction.ListReactionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reaction.ListReactionsResponse: + r"""Call the list reactions method over HTTP. + + Args: + request (~.reaction.ListReactionsRequest): + The request object. Lists reactions to a message. + 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: + ~.reaction.ListReactionsResponse: + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=spaces/*/messages/*}/reactions", + }, + ] + request, metadata = self._interceptor.pre_list_reactions(request, metadata) + pb_request = reaction.ListReactionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = reaction.ListReactionsResponse() + pb_resp = reaction.ListReactionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_reactions(resp) + return resp + + class _ListSpaces(ChatServiceRestStub): + def __hash__(self): + return hash("ListSpaces") + + def __call__( + self, + request: space.ListSpacesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.ListSpacesResponse: + r"""Call the list spaces method over HTTP. + + Args: + request (~.space.ListSpacesRequest): + The request object. A request to list the spaces the + caller is a member of. + 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: + ~.space.ListSpacesResponse: + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/spaces", + }, + ] + request, metadata = self._interceptor.pre_list_spaces(request, metadata) + pb_request = space.ListSpacesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = space.ListSpacesResponse() + pb_resp = space.ListSpacesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_spaces(resp) + return resp + + class _SetUpSpace(ChatServiceRestStub): + def __hash__(self): + return hash("SetUpSpace") + + __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 + } + + def __call__( + self, + request: space_setup.SetUpSpaceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> space.Space: + r"""Call the set up space method over HTTP. + + Args: + request (~.space_setup.SetUpSpaceRequest): + The request 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. + + Returns: + ~.space.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/spaces:setup", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_set_up_space(request, metadata) + pb_request = space_setup.SetUpSpaceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = space.Space() + pb_resp = space.Space.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_up_space(resp) + return resp + + class _UpdateMessage(ChatServiceRestStub): + def __hash__(self): + return hash("UpdateMessage") + + __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 + } + + def __call__( + self, + request: gc_message.UpdateMessageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_message.Message: + r"""Call the update message method over HTTP. + + Args: + request (~.gc_message.UpdateMessageRequest): + The request 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. + + Returns: + ~.gc_message.Message: + A message in a Google Chat space. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "put", + "uri": "/v1/{message.name=spaces/*/messages/*}", + "body": "message", + }, + { + "method": "patch", + "uri": "/v1/{message.name=spaces/*/messages/*}", + "body": "message", + }, + ] + request, metadata = self._interceptor.pre_update_message(request, metadata) + pb_request = gc_message.UpdateMessageRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gc_message.Message() + pb_resp = gc_message.Message.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_message(resp) + return resp + + class _UpdateSpace(ChatServiceRestStub): + def __hash__(self): + return hash("UpdateSpace") + + __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 + } + + def __call__( + self, + request: gc_space.UpdateSpaceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gc_space.Space: + r"""Call the update space method over HTTP. + + Args: + request (~.gc_space.UpdateSpaceRequest): + The request object. A request to update a single space. + 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: + ~.gc_space.Space: + A space in Google Chat. Spaces are + conversations between two or more users + or 1:1 messages between a user and a + Chat app. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{space.name=spaces/*}", + "body": "space", + }, + ] + request, metadata = self._interceptor.pre_update_space(request, metadata) + pb_request = gc_space.UpdateSpaceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gc_space.Space() + pb_resp = gc_space.Space.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_space(resp) + return resp + + class _UploadAttachment(ChatServiceRestStub): + def __hash__(self): + return hash("UploadAttachment") + + __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 + } + + def __call__( + self, + request: attachment.UploadAttachmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> attachment.UploadAttachmentResponse: + r"""Call the upload attachment method over HTTP. + + Args: + request (~.attachment.UploadAttachmentRequest): + The request 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. + + Returns: + ~.attachment.UploadAttachmentResponse: + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=spaces/*}/attachments:upload", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_upload_attachment( + request, metadata + ) + pb_request = attachment.UploadAttachmentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = attachment.UploadAttachmentResponse() + pb_resp = attachment.UploadAttachmentResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_upload_attachment(resp) + return resp + + @property + def complete_import_space( + self, + ) -> Callable[ + [space.CompleteImportSpaceRequest], space.CompleteImportSpaceResponse + ]: + # 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._CompleteImportSpace(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_membership( + self, + ) -> Callable[[gc_membership.CreateMembershipRequest], gc_membership.Membership]: + # 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._CreateMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_message( + self, + ) -> Callable[[gc_message.CreateMessageRequest], gc_message.Message]: + # 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._CreateMessage(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_reaction( + self, + ) -> Callable[[gc_reaction.CreateReactionRequest], gc_reaction.Reaction]: + # 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._CreateReaction(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_space(self) -> Callable[[gc_space.CreateSpaceRequest], gc_space.Space]: + # 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._CreateSpace(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_membership( + self, + ) -> Callable[[membership.DeleteMembershipRequest], membership.Membership]: + # 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._DeleteMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_message( + self, + ) -> Callable[[message.DeleteMessageRequest], empty_pb2.Empty]: + # 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._DeleteMessage(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_reaction( + self, + ) -> Callable[[reaction.DeleteReactionRequest], empty_pb2.Empty]: + # 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._DeleteReaction(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_space(self) -> Callable[[space.DeleteSpaceRequest], empty_pb2.Empty]: + # 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._DeleteSpace(self._session, self._host, self._interceptor) # type: ignore + + @property + def find_direct_message( + self, + ) -> Callable[[space.FindDirectMessageRequest], space.Space]: + # 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._FindDirectMessage(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_attachment( + self, + ) -> Callable[[attachment.GetAttachmentRequest], attachment.Attachment]: + # 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._GetAttachment(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_membership( + self, + ) -> Callable[[membership.GetMembershipRequest], membership.Membership]: + # 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._GetMembership(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_message(self) -> Callable[[message.GetMessageRequest], message.Message]: + # 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._GetMessage(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_space(self) -> Callable[[space.GetSpaceRequest], space.Space]: + # 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._GetSpace(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_memberships( + self, + ) -> Callable[ + [membership.ListMembershipsRequest], membership.ListMembershipsResponse + ]: + # 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._ListMemberships(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_messages( + self, + ) -> Callable[[message.ListMessagesRequest], message.ListMessagesResponse]: + # 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._ListMessages(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_reactions( + self, + ) -> Callable[[reaction.ListReactionsRequest], reaction.ListReactionsResponse]: + # 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._ListReactions(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_spaces( + self, + ) -> Callable[[space.ListSpacesRequest], space.ListSpacesResponse]: + # 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._ListSpaces(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_up_space(self) -> Callable[[space_setup.SetUpSpaceRequest], space.Space]: + # 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._SetUpSpace(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_message( + self, + ) -> Callable[[gc_message.UpdateMessageRequest], gc_message.Message]: + # 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._UpdateMessage(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_space(self) -> Callable[[gc_space.UpdateSpaceRequest], gc_space.Space]: + # 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._UpdateSpace(self._session, self._host, self._interceptor) # type: ignore + + @property + def upload_attachment( + self, + ) -> Callable[ + [attachment.UploadAttachmentRequest], attachment.UploadAttachmentResponse + ]: + # 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._UploadAttachment(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ChatServiceRestTransport",) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/__init__.py b/packages/google-apps-chat/google/apps/chat_v1/types/__init__.py new file mode 100644 index 000000000000..0a3abba8cb83 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/__init__.py @@ -0,0 +1,146 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .action_status import ActionStatus +from .annotation import ( + Annotation, + AnnotationType, + SlashCommandMetadata, + UserMentionMetadata, +) +from .attachment import ( + Attachment, + AttachmentDataRef, + DriveDataRef, + GetAttachmentRequest, + UploadAttachmentRequest, + UploadAttachmentResponse, +) +from .contextual_addon import ContextualAddOnMarkup +from .deletion_metadata import DeletionMetadata +from .group import Group +from .history_state import HistoryState +from .matched_url import MatchedUrl +from .membership import ( + CreateMembershipRequest, + DeleteMembershipRequest, + GetMembershipRequest, + ListMembershipsRequest, + ListMembershipsResponse, + Membership, +) +from .message import ( + ActionResponse, + AttachedGif, + CardWithId, + CreateMessageRequest, + DeleteMessageRequest, + Dialog, + DialogAction, + GetMessageRequest, + ListMessagesRequest, + ListMessagesResponse, + Message, + QuotedMessageMetadata, + Thread, + UpdateMessageRequest, +) +from .reaction import ( + CreateReactionRequest, + CustomEmoji, + DeleteReactionRequest, + Emoji, + EmojiReactionSummary, + ListReactionsRequest, + ListReactionsResponse, + Reaction, +) +from .slash_command import SlashCommand +from .space import ( + CompleteImportSpaceRequest, + CompleteImportSpaceResponse, + CreateSpaceRequest, + DeleteSpaceRequest, + FindDirectMessageRequest, + GetSpaceRequest, + ListSpacesRequest, + ListSpacesResponse, + Space, + UpdateSpaceRequest, +) +from .space_setup import SetUpSpaceRequest +from .user import User +from .widgets import WidgetMarkup + +__all__ = ( + "ActionStatus", + "Annotation", + "SlashCommandMetadata", + "UserMentionMetadata", + "AnnotationType", + "Attachment", + "AttachmentDataRef", + "DriveDataRef", + "GetAttachmentRequest", + "UploadAttachmentRequest", + "UploadAttachmentResponse", + "ContextualAddOnMarkup", + "DeletionMetadata", + "Group", + "HistoryState", + "MatchedUrl", + "CreateMembershipRequest", + "DeleteMembershipRequest", + "GetMembershipRequest", + "ListMembershipsRequest", + "ListMembershipsResponse", + "Membership", + "ActionResponse", + "AttachedGif", + "CardWithId", + "CreateMessageRequest", + "DeleteMessageRequest", + "Dialog", + "DialogAction", + "GetMessageRequest", + "ListMessagesRequest", + "ListMessagesResponse", + "Message", + "QuotedMessageMetadata", + "Thread", + "UpdateMessageRequest", + "CreateReactionRequest", + "CustomEmoji", + "DeleteReactionRequest", + "Emoji", + "EmojiReactionSummary", + "ListReactionsRequest", + "ListReactionsResponse", + "Reaction", + "SlashCommand", + "CompleteImportSpaceRequest", + "CompleteImportSpaceResponse", + "CreateSpaceRequest", + "DeleteSpaceRequest", + "FindDirectMessageRequest", + "GetSpaceRequest", + "ListSpacesRequest", + "ListSpacesResponse", + "Space", + "UpdateSpaceRequest", + "SetUpSpaceRequest", + "User", + "WidgetMarkup", +) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/action_status.py b/packages/google-apps-chat/google/apps/chat_v1/types/action_status.py new file mode 100644 index 000000000000..c63e7b400816 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/action_status.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.rpc import code_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "ActionStatus", + }, +) + + +class ActionStatus(proto.Message): + r"""Represents the status for a request to either invoke or submit a + `dialog `__. + + Attributes: + status_code (google.rpc.code_pb2.Code): + The status code. + user_facing_message (str): + The message to send users about the status of their request. + If unset, a generic message based on the ``status_code`` is + sent. + """ + + status_code: code_pb2.Code = proto.Field( + proto.ENUM, + number=1, + enum=code_pb2.Code, + ) + user_facing_message: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/annotation.py b/packages/google-apps-chat/google/apps/chat_v1/types/annotation.py new file mode 100644 index 000000000000..a8d4e65599be --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/annotation.py @@ -0,0 +1,231 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 + +from google.apps.chat_v1.types import user as gc_user + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "AnnotationType", + "Annotation", + "UserMentionMetadata", + "SlashCommandMetadata", + }, +) + + +class AnnotationType(proto.Enum): + r"""Type of the annotation. + + Values: + ANNOTATION_TYPE_UNSPECIFIED (0): + Default value for the enum. Don't use. + USER_MENTION (1): + A user is mentioned. + SLASH_COMMAND (2): + A slash command is invoked. + """ + ANNOTATION_TYPE_UNSPECIFIED = 0 + USER_MENTION = 1 + SLASH_COMMAND = 2 + + +class Annotation(proto.Message): + r"""Output only. Annotations associated with the plain-text body of the + message. To add basic formatting to a text message, see `Format text + messages `__. + + Example plain-text message body: + + :: + + Hello @FooBot how are you!" + + The corresponding annotations metadata: + + :: + + "annotations":[{ + "type":"USER_MENTION", + "startIndex":6, + "length":7, + "userMention": { + "user": { + "name":"users/{user}", + "displayName":"FooBot", + "avatarUrl":"https://goo.gl/aeDtrS", + "type":"BOT" + }, + "type":"MENTION" + } + }] + + 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: + type_ (google.apps.chat_v1.types.AnnotationType): + The type of this annotation. + start_index (int): + Start index (0-based, inclusive) in the + plain-text message body this annotation + corresponds to. + + This field is a member of `oneof`_ ``_start_index``. + length (int): + Length of the substring in the plain-text + message body this annotation corresponds to. + user_mention (google.apps.chat_v1.types.UserMentionMetadata): + The metadata of user mention. + + This field is a member of `oneof`_ ``metadata``. + slash_command (google.apps.chat_v1.types.SlashCommandMetadata): + The metadata for a slash command. + + This field is a member of `oneof`_ ``metadata``. + """ + + type_: "AnnotationType" = proto.Field( + proto.ENUM, + number=1, + enum="AnnotationType", + ) + start_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + length: int = proto.Field( + proto.INT32, + number=3, + ) + user_mention: "UserMentionMetadata" = proto.Field( + proto.MESSAGE, + number=4, + oneof="metadata", + message="UserMentionMetadata", + ) + slash_command: "SlashCommandMetadata" = proto.Field( + proto.MESSAGE, + number=5, + oneof="metadata", + message="SlashCommandMetadata", + ) + + +class UserMentionMetadata(proto.Message): + r"""Annotation metadata for user mentions (@). + + Attributes: + user (google.apps.chat_v1.types.User): + The user mentioned. + type_ (google.apps.chat_v1.types.UserMentionMetadata.Type): + The type of user mention. + """ + + class Type(proto.Enum): + r""" + + Values: + TYPE_UNSPECIFIED (0): + Default value for the enum. Don't use. + ADD (1): + Add user to space. + MENTION (2): + Mention user in space. + """ + TYPE_UNSPECIFIED = 0 + ADD = 1 + MENTION = 2 + + user: gc_user.User = proto.Field( + proto.MESSAGE, + number=1, + message=gc_user.User, + ) + type_: Type = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + + +class SlashCommandMetadata(proto.Message): + r"""Annotation metadata for slash commands (/). + + Attributes: + bot (google.apps.chat_v1.types.User): + The Chat app whose command was invoked. + type_ (google.apps.chat_v1.types.SlashCommandMetadata.Type): + The type of slash command. + command_name (str): + The name of the invoked slash command. + command_id (int): + The command ID of the invoked slash command. + triggers_dialog (bool): + Indicates whether the slash command is for a + dialog. + """ + + class Type(proto.Enum): + r""" + + Values: + TYPE_UNSPECIFIED (0): + Default value for the enum. Don't use. + ADD (1): + Add Chat app to space. + INVOKE (2): + Invoke slash command in space. + """ + TYPE_UNSPECIFIED = 0 + ADD = 1 + INVOKE = 2 + + bot: gc_user.User = proto.Field( + proto.MESSAGE, + number=1, + message=gc_user.User, + ) + type_: Type = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + command_name: str = proto.Field( + proto.STRING, + number=3, + ) + command_id: int = proto.Field( + proto.INT64, + number=4, + ) + triggers_dialog: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/attachment.py b/packages/google-apps-chat/google/apps/chat_v1/types/attachment.py new file mode 100644 index 000000000000..10fb76e7b71f --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/attachment.py @@ -0,0 +1,228 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.chat.v1", + manifest={ + "Attachment", + "DriveDataRef", + "AttachmentDataRef", + "GetAttachmentRequest", + "UploadAttachmentRequest", + "UploadAttachmentResponse", + }, +) + + +class Attachment(proto.Message): + r"""An attachment in Google Chat. + + 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: + name (str): + Resource name of the attachment, in the form + ``spaces/*/messages/*/attachments/*``. + content_name (str): + Output only. The original file name for the + content, not the full path. + content_type (str): + Output only. The content type (MIME type) of + the file. + attachment_data_ref (google.apps.chat_v1.types.AttachmentDataRef): + A reference to the attachment data. This + field is used with the media API to download the + attachment data. + + This field is a member of `oneof`_ ``data_ref``. + drive_data_ref (google.apps.chat_v1.types.DriveDataRef): + Output only. A reference to the Google Drive + attachment. This field is used with the Google + Drive API. + + This field is a member of `oneof`_ ``data_ref``. + thumbnail_uri (str): + Output only. The thumbnail URL which should + be used to preview the attachment to a human + user. Chat apps shouldn't use this URL to + download attachment content. + download_uri (str): + Output only. The download URL which should be + used to allow a human user to download the + attachment. Chat apps shouldn't use this URL to + download attachment content. + source (google.apps.chat_v1.types.Attachment.Source): + Output only. The source of the attachment. + """ + + class Source(proto.Enum): + r""" + + Values: + SOURCE_UNSPECIFIED (0): + No description available. + DRIVE_FILE (1): + No description available. + UPLOADED_CONTENT (2): + No description available. + """ + SOURCE_UNSPECIFIED = 0 + DRIVE_FILE = 1 + UPLOADED_CONTENT = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + content_name: str = proto.Field( + proto.STRING, + number=2, + ) + content_type: str = proto.Field( + proto.STRING, + number=3, + ) + attachment_data_ref: "AttachmentDataRef" = proto.Field( + proto.MESSAGE, + number=4, + oneof="data_ref", + message="AttachmentDataRef", + ) + drive_data_ref: "DriveDataRef" = proto.Field( + proto.MESSAGE, + number=7, + oneof="data_ref", + message="DriveDataRef", + ) + thumbnail_uri: str = proto.Field( + proto.STRING, + number=5, + ) + download_uri: str = proto.Field( + proto.STRING, + number=6, + ) + source: Source = proto.Field( + proto.ENUM, + number=9, + enum=Source, + ) + + +class DriveDataRef(proto.Message): + r"""A reference to the data of a drive attachment. + + Attributes: + drive_file_id (str): + The ID for the drive file. Use with the Drive + API. + """ + + drive_file_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AttachmentDataRef(proto.Message): + r""" + + Attributes: + resource_name (str): + The resource name of the attachment data. + This field is used with the media API to + download the attachment data. + attachment_upload_token (str): + Opaque token containing a reference to an + uploaded attachment. Treated by clients as an + opaque string and used to create or update Chat + messages with attachments. + """ + + resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + attachment_upload_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetAttachmentRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. Resource name of the attachment, in the form + ``spaces/*/messages/*/attachments/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UploadAttachmentRequest(proto.Message): + r""" + + Attributes: + parent (str): + Required. Resource name of the Chat space in + which the attachment is uploaded. Format + "spaces/{space}". + filename (str): + Required. The filename of the attachment, + including the file extension. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filename: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UploadAttachmentResponse(proto.Message): + r""" + + Attributes: + attachment_data_ref (google.apps.chat_v1.types.AttachmentDataRef): + Reference to the uploaded attachment. + """ + + attachment_data_ref: "AttachmentDataRef" = proto.Field( + proto.MESSAGE, + number=1, + message="AttachmentDataRef", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/chat_service.py b/packages/google-apps-chat/google/apps/chat_v1/types/chat_service.py new file mode 100644 index 000000000000..3e89e9ac7ba7 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/chat_service.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={}, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/contextual_addon.py b/packages/google-apps-chat/google/apps/chat_v1/types/contextual_addon.py new file mode 100644 index 000000000000..0a5a9627d2d0 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/contextual_addon.py @@ -0,0 +1,187 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 + +from google.apps.chat_v1.types import widgets as gc_widgets + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "ContextualAddOnMarkup", + }, +) + + +class ContextualAddOnMarkup(proto.Message): + r"""The markup for developers to specify the contents of a + contextual AddOn. + + """ + + class Card(proto.Message): + r"""A card is a UI element that can contain UI widgets such as + text and images. + + Attributes: + header (google.apps.chat_v1.types.ContextualAddOnMarkup.Card.CardHeader): + The header of the card. A header usually + contains a title and an image. + sections (MutableSequence[google.apps.chat_v1.types.ContextualAddOnMarkup.Card.Section]): + Sections are separated by a line divider. + card_actions (MutableSequence[google.apps.chat_v1.types.ContextualAddOnMarkup.Card.CardAction]): + The actions of this card. + name (str): + Name of the card. + """ + + class CardHeader(proto.Message): + r""" + + Attributes: + title (str): + The title must be specified. The header has a + fixed height: if both a title and subtitle is + specified, each takes up one line. If only the + title is specified, it takes up both lines. + subtitle (str): + The subtitle of the card header. + image_style (google.apps.chat_v1.types.ContextualAddOnMarkup.Card.CardHeader.ImageStyle): + The image's type (for example, square border + or circular border). + image_url (str): + The URL of the image in the card header. + """ + + class ImageStyle(proto.Enum): + r""" + + Values: + IMAGE_STYLE_UNSPECIFIED (0): + No description available. + IMAGE (1): + Square border. + AVATAR (2): + Circular border. + """ + IMAGE_STYLE_UNSPECIFIED = 0 + IMAGE = 1 + AVATAR = 2 + + title: str = proto.Field( + proto.STRING, + number=1, + ) + subtitle: str = proto.Field( + proto.STRING, + number=2, + ) + image_style: "ContextualAddOnMarkup.Card.CardHeader.ImageStyle" = ( + proto.Field( + proto.ENUM, + number=3, + enum="ContextualAddOnMarkup.Card.CardHeader.ImageStyle", + ) + ) + image_url: str = proto.Field( + proto.STRING, + number=4, + ) + + class Section(proto.Message): + r"""A section contains a collection of widgets that are rendered + (vertically) in the order that they are specified. Across all + platforms, cards have a narrow fixed width, so + there's currently no need for layout properties (for example, + float). + + Attributes: + header (str): + The header of the section. Formatted text is supported. For + more information about formatting text, see `Formatting text + in Google Chat + apps `__ + and `Formatting text in Google Workspace + Add-ons `__. + widgets (MutableSequence[google.apps.chat_v1.types.WidgetMarkup]): + A section must contain at least one widget. + """ + + header: str = proto.Field( + proto.STRING, + number=1, + ) + widgets: MutableSequence[gc_widgets.WidgetMarkup] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gc_widgets.WidgetMarkup, + ) + + class CardAction(proto.Message): + r"""A card action is + the action associated with the card. For an invoice card, a + typical action would be: delete invoice, email invoice or open + the invoice in browser. + + Not supported by Google Chat apps. + + Attributes: + action_label (str): + The label used to be displayed in the action + menu item. + on_click (google.apps.chat_v1.types.WidgetMarkup.OnClick): + The onclick action for this action item. + """ + + action_label: str = proto.Field( + proto.STRING, + number=1, + ) + on_click: gc_widgets.WidgetMarkup.OnClick = proto.Field( + proto.MESSAGE, + number=2, + message=gc_widgets.WidgetMarkup.OnClick, + ) + + header: "ContextualAddOnMarkup.Card.CardHeader" = proto.Field( + proto.MESSAGE, + number=1, + message="ContextualAddOnMarkup.Card.CardHeader", + ) + sections: MutableSequence[ + "ContextualAddOnMarkup.Card.Section" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="ContextualAddOnMarkup.Card.Section", + ) + card_actions: MutableSequence[ + "ContextualAddOnMarkup.Card.CardAction" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="ContextualAddOnMarkup.Card.CardAction", + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/deletion_metadata.py b/packages/google-apps-chat/google/apps/chat_v1/types/deletion_metadata.py new file mode 100644 index 000000000000..e21764228754 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/deletion_metadata.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.chat.v1", + manifest={ + "DeletionMetadata", + }, +) + + +class DeletionMetadata(proto.Message): + r"""Information about a deleted message. A message is deleted when + ``delete_time`` is set. + + Attributes: + deletion_type (google.apps.chat_v1.types.DeletionMetadata.DeletionType): + Indicates who deleted the message. + """ + + class DeletionType(proto.Enum): + r"""Who deleted the message and how it was deleted. + + Values: + DELETION_TYPE_UNSPECIFIED (0): + This value is unused. + CREATOR (1): + User deleted their own message. + SPACE_OWNER (2): + The space owner deleted the message. + ADMIN (3): + A Google Workspace admin deleted the message. + APP_MESSAGE_EXPIRY (4): + A Chat app deleted its own message when it + expired. + CREATOR_VIA_APP (5): + A Chat app deleted the message on behalf of + the user. + SPACE_OWNER_VIA_APP (6): + A Chat app deleted the message on behalf of + the space owner. + """ + DELETION_TYPE_UNSPECIFIED = 0 + CREATOR = 1 + SPACE_OWNER = 2 + ADMIN = 3 + APP_MESSAGE_EXPIRY = 4 + CREATOR_VIA_APP = 5 + SPACE_OWNER_VIA_APP = 6 + + deletion_type: DeletionType = proto.Field( + proto.ENUM, + number=1, + enum=DeletionType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/group.py b/packages/google-apps-chat/google/apps/chat_v1/types/group.py new file mode 100644 index 000000000000..9da68edab8bb --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/group.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.chat.v1", + manifest={ + "Group", + }, +) + + +class Group(proto.Message): + r"""A Google Group in Google Chat. + + Attributes: + name (str): + Resource name for a Google Group. + + Represents a + `group `__ + in Cloud Identity Groups API. + + Format: groups/{group} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/history_state.py b/packages/google-apps-chat/google/apps/chat_v1/types/history_state.py new file mode 100644 index 000000000000..e165280fc302 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/history_state.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.chat.v1", + manifest={ + "HistoryState", + }, +) + + +class HistoryState(proto.Enum): + r"""The history state for messages and spaces. Specifies how long + messages and conversation threads are kept after creation. + + Values: + HISTORY_STATE_UNSPECIFIED (0): + Default value. Do not use. + HISTORY_OFF (1): + History off. `Messages and threads are kept for 24 + hours `__. + HISTORY_ON (2): + History on. The organization's `Vault retention + rules `__ + specify for how long messages and threads are kept. + """ + HISTORY_STATE_UNSPECIFIED = 0 + HISTORY_OFF = 1 + HISTORY_ON = 2 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/matched_url.py b/packages/google-apps-chat/google/apps/chat_v1/types/matched_url.py new file mode 100644 index 000000000000..558b7cfa8699 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/matched_url.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.chat.v1", + manifest={ + "MatchedUrl", + }, +) + + +class MatchedUrl(proto.Message): + r"""A matched URL in a Chat message. Chat apps can preview matched URLs. + For more information, see `Preview + links `__. + + Attributes: + url (str): + Output only. The URL that was matched. + """ + + url: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/membership.py b/packages/google-apps-chat/google/apps/chat_v1/types/membership.py new file mode 100644 index 000000000000..d02a2473f1a1 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/membership.py @@ -0,0 +1,421 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.apps.chat_v1.types import group, user + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "Membership", + "CreateMembershipRequest", + "ListMembershipsRequest", + "ListMembershipsResponse", + "GetMembershipRequest", + "DeleteMembershipRequest", + }, +) + + +class Membership(proto.Message): + r"""Represents a membership relation in Google Chat, such as + whether a user or Chat app is invited to, part of, or absent + from a space. + + 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: + name (str): + Resource name of the membership, assigned by the server. + + Format: ``spaces/{space}/members/{member}`` + state (google.apps.chat_v1.types.Membership.MembershipState): + Output only. State of the membership. + role (google.apps.chat_v1.types.Membership.MembershipRole): + Optional. User's role within a Chat space, which determines + their permitted actions in the space. + + `Developer + Preview `__: + This field can only be used as input in + ``UpdateMembership``. + member (google.apps.chat_v1.types.User): + The Google Chat user or app the membership corresponds to. + If your Chat app `authenticates as a + user `__, + the output populates the + `user `__ + ``name`` and ``type``. + + This field is a member of `oneof`_ ``memberType``. + group_member (google.apps.chat_v1.types.Group): + The Google Group the membership corresponds + to. Only supports read operations. Other + operations, like creating or updating a + membership, aren't currently supported. + + This field is a member of `oneof`_ ``memberType``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Immutable. The creation time of the + membership, such as when a member joined or was + invited to join a space. This field is output + only, except when used to import historical + memberships in import mode spaces. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Immutable. The deletion time of the + membership, such as when a member left or was + removed from a space. This field is output only, + except when used to import historical + memberships in import mode spaces. + """ + + class MembershipState(proto.Enum): + r"""Specifies the member's relationship with a space. Other + membership states might be supported in the future. + + Values: + MEMBERSHIP_STATE_UNSPECIFIED (0): + Default value. Don't use. + JOINED (1): + The user is added to the space, and can + participate in the space. + INVITED (2): + The user is invited to join the space, but + hasn't joined it. + NOT_A_MEMBER (3): + The user doesn't belong to the space and + doesn't have a pending invitation to join the + space. + """ + MEMBERSHIP_STATE_UNSPECIFIED = 0 + JOINED = 1 + INVITED = 2 + NOT_A_MEMBER = 3 + + class MembershipRole(proto.Enum): + r"""Represents a user's permitted actions in a Chat space. More + enum values might be added in the future. + + Values: + MEMBERSHIP_ROLE_UNSPECIFIED (0): + Default value. For + [users][google.chat.v1.Membership.member]: they aren't a + member of the space, but can be invited. For [Google + Groups][google.chat.v1.Membership.group_member]: they're + always assigned this role (other enum values might be used + in the future). + ROLE_MEMBER (1): + A member of the space. The user has basic + permissions, like sending messages to the space. + In 1:1 and unnamed group conversations, everyone + has this role. + ROLE_MANAGER (2): + A space manager. The user has all basic permissions plus + administrative permissions that let them manage the space, + like adding or removing members. Only supported in + [SpaceType.SPACE][google.chat.v1.Space.SpaceType]. + """ + MEMBERSHIP_ROLE_UNSPECIFIED = 0 + ROLE_MEMBER = 1 + ROLE_MANAGER = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: MembershipState = proto.Field( + proto.ENUM, + number=2, + enum=MembershipState, + ) + role: MembershipRole = proto.Field( + proto.ENUM, + number=7, + enum=MembershipRole, + ) + member: user.User = proto.Field( + proto.MESSAGE, + number=3, + oneof="memberType", + message=user.User, + ) + group_member: group.Group = proto.Field( + proto.MESSAGE, + number=5, + oneof="memberType", + message=group.Group, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + + +class CreateMembershipRequest(proto.Message): + r""" + + Attributes: + parent (str): + Required. The resource name of the space for + which to create the membership. + + Format: spaces/{space} + membership (google.apps.chat_v1.types.Membership): + Required. The membership relation to create. The + ``memberType`` field must contain a user with the + ``user.name`` and ``user.type`` fields populated. The server + will assign a resource name and overwrite anything + specified. When a Chat app creates a membership relation for + a human user, it must use the ``chat.memberships`` scope, + set ``user.type`` to ``HUMAN``, and set ``user.name`` with + format ``users/{user}``, where ``{user}`` can be the email + address for the user. For users in the same Workspace + organization ``{user}`` can also be the ``id`` of the + `person `__ + from the People API, or the ``id`` for the user in the + Directory API. For example, if the People API Person profile + ID for ``user@example.com`` is ``123456789``, you can add + the user to the space by setting the + ``membership.member.name`` to ``users/user@example.com`` or + ``users/123456789``. When a Chat app creates a membership + relation for itself, it must use the + ``chat.memberships.app`` scope, set ``user.type`` to + ``BOT``, and set ``user.name`` to ``users/app``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + membership: "Membership" = proto.Field( + proto.MESSAGE, + number=2, + message="Membership", + ) + + +class ListMembershipsRequest(proto.Message): + r""" + + Attributes: + parent (str): + Required. The resource name of the space for + which to fetch a membership list. + + Format: spaces/{space} + page_size (int): + Optional. The maximum number of memberships to return. The + service might return fewer than this value. + + If unspecified, at most 100 memberships are returned. + + The maximum value is 1,000. If you use a value more than + 1,000, it's automatically changed to 1,000. + + Negative values return an ``INVALID_ARGUMENT`` error. + page_token (str): + Optional. A page token, received from a + previous call to list memberships. Provide this + parameter to retrieve the subsequent page. + + When paginating, all other parameters provided + should match the call that provided the page + token. Passing different values to the other + parameters might lead to unexpected results. + filter (str): + Optional. A query filter. + + You can filter memberships by a member's role + (```role`` `__) + and type + (```member.type`` `__). + + To filter by role, set ``role`` to ``ROLE_MEMBER`` or + ``ROLE_MANAGER``. + + To filter by type, set ``member.type`` to ``HUMAN`` or + ``BOT``. + + To filter by both role and type, use the ``AND`` operator. + To filter by either role or type, use the ``OR`` operator. + + For example, the following queries are valid: + + :: + + role = "ROLE_MANAGER" OR role = "ROLE_MEMBER" + member.type = "HUMAN" AND role = "ROLE_MANAGER" + + The following queries are invalid: + + :: + + member.type = "HUMAN" AND member.type = "BOT" + role = "ROLE_MANAGER" AND role = "ROLE_MEMBER" + + Invalid queries are rejected by the server with an + ``INVALID_ARGUMENT`` error. + show_groups (bool): + Optional. When ``true``, also returns memberships associated + with a [Google + Group][google.chat.v1.Membership.group_member], in addition + to other types of memberships. If a + [filter][google.chat.v1.ListMembershipsRequest.filter] is + set, [Google Group][google.chat.v1.Membership.group_member] + memberships that don't match the filter criteria aren't + returned. + show_invited (bool): + Optional. When ``true``, also returns memberships associated + with + [invited][google.chat.v1.Membership.MembershipState.INVITED] + members, in addition to other types of memberships. If a + filter is set, + [invited][google.chat.v1.Membership.MembershipState.INVITED] + memberships that don't match the filter criteria aren't + returned. + + Currently requires `user + authentication `__. + """ + + 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, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + show_groups: bool = proto.Field( + proto.BOOL, + number=6, + ) + show_invited: bool = proto.Field( + proto.BOOL, + number=7, + ) + + +class ListMembershipsResponse(proto.Message): + r""" + + Attributes: + memberships (MutableSequence[google.apps.chat_v1.types.Membership]): + Unordered list. List of memberships in the + requested (or first) page. + next_page_token (str): + A token that you can send as ``pageToken`` to retrieve the + next page of results. If empty, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + memberships: MutableSequence["Membership"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Membership", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetMembershipRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. Resource name of the membership to retrieve. + + To get the app's own membership, you can optionally use + ``spaces/{space}/members/app``. + + Format: ``spaces/{space}/members/{member}`` or + ``spaces/{space}/members/app`` + + When `authenticated as a + user `__, + you can use the user's email as an alias for ``{member}``. + For example, ``spaces/{space}/members/example@gmail.com`` + where ``example@gmail.com`` is the email of the Google Chat + user. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteMembershipRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. Resource name of the membership to delete. Chat + apps can delete human users' or their own memberships. Chat + apps can't delete other apps' memberships. + + When deleting a human membership, requires the + ``chat.memberships`` scope and + ``spaces/{space}/members/{member}`` format. You can use the + email as an alias for ``{member}``. For example, + ``spaces/{space}/members/example@gmail.com`` where + ``example@gmail.com`` is the email of the Google Chat user. + + When deleting an app membership, requires the + ``chat.memberships.app`` scope and + ``spaces/{space}/members/app`` format. + + Format: ``spaces/{space}/members/{member}`` or + ``spaces/{space}/members/app``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/message.py b/packages/google-apps-chat/google/apps/chat_v1/types/message.py new file mode 100644 index 000000000000..20b377eda63d --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/message.py @@ -0,0 +1,996 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.apps.card_v1.types import card as gac_card +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.apps.chat_v1.types import action_status as gc_action_status +from google.apps.chat_v1.types import annotation +from google.apps.chat_v1.types import attachment as gc_attachment +from google.apps.chat_v1.types import contextual_addon +from google.apps.chat_v1.types import deletion_metadata as gc_deletion_metadata +from google.apps.chat_v1.types import matched_url as gc_matched_url +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import slash_command as gc_slash_command +from google.apps.chat_v1.types import space as gc_space +from google.apps.chat_v1.types import user + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "Message", + "AttachedGif", + "QuotedMessageMetadata", + "Thread", + "ActionResponse", + "GetMessageRequest", + "DeleteMessageRequest", + "UpdateMessageRequest", + "CreateMessageRequest", + "ListMessagesRequest", + "ListMessagesResponse", + "DialogAction", + "Dialog", + "CardWithId", + }, +) + + +class Message(proto.Message): + r"""A message in a Google Chat space. + + Attributes: + name (str): + Resource name of the message. + + Format: ``spaces/{space}/messages/{message}`` + + Where ``{space}`` is the ID of the space where the message + is posted and ``{message}`` is a system-assigned ID for the + message. For example, + ``spaces/AAAAAAAAAAA/messages/BBBBBBBBBBB.BBBBBBBBBBB``. + + If you set a custom ID when you create a message, you can + use this ID to specify the message in a request by replacing + ``{message}`` with the value from the + ``clientAssignedMessageId`` field. For example, + ``spaces/AAAAAAAAAAA/messages/client-custom-name``. For + details, see `Name a + message `__. + sender (google.apps.chat_v1.types.User): + Output only. The user who created the message. If your Chat + app `authenticates as a + user `__, + the output populates the + `user `__ + ``name`` and ``type``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Immutable. For spaces created in + Chat, the time at which the message was created. + This field is output only, except when used in + import mode spaces. + + For import mode spaces, set this field to the + historical timestamp at which the message was + created in the source in order to preserve the + original creation time. + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the message + was last edited by a user. If the message has + never been edited, this field is empty. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the message + was deleted in Google Chat. If the message is + never deleted, this field is empty. + text (str): + Plain-text body of the message. The first link to an image, + video, or web page generates a `preview + chip `__. + You can also `@mention a Google Chat + user `__, + or everyone in the space. + + To learn about creating text messages, see `Send a text + message `__. + formatted_text (str): + Output only. Contains the message ``text`` with markups + added to communicate formatting. This field might not + capture all formatting visible in the UI, but includes the + following: + + - `Markup + syntax `__ + for bold, italic, strikethrough, monospace, and monospace + block. + + - `User + mentions `__ + using the format ````. + + - Custom hyperlinks using the format + ``<{url}|{rendered_text}>`` where the first string is the + URL and the second is the rendered text—for example, + ````. + + - Custom emoji using the format ``:{emoji_name}:``—for + example, ``:smile:``. This doesn't apply to Unicode + emoji, such as ``U+1F600`` for a grinning face emoji. + + For more information, see `View text formatting sent in a + message `__ + cards (MutableSequence[google.apps.chat_v1.types.ContextualAddOnMarkup.Card]): + Deprecated: Use ``cards_v2`` instead. + + Rich, formatted, and interactive cards that you can use to + display UI elements such as: formatted texts, buttons, and + clickable images. Cards are normally displayed below the + plain-text body of the message. ``cards`` and ``cards_v2`` + can have a maximum size of 32 KB. + cards_v2 (MutableSequence[google.apps.chat_v1.types.CardWithId]): + An array of + `cards `__. + + Only Chat apps can create cards. If your Chat app + `authenticates as a + user `__, + the messages can't contain cards. + + To learn about cards and how to create them, see `Design + dynamic, interactive, and consistent UIs with + cards `__. + + `Card + builder `__ + annotations (MutableSequence[google.apps.chat_v1.types.Annotation]): + Output only. Annotations associated with the ``text`` in + this message. + thread (google.apps.chat_v1.types.Thread): + The thread the message belongs to. For example usage, see + `Start or reply to a message + thread `__. + space (google.apps.chat_v1.types.Space): + If your Chat app `authenticates as a + user `__, + the output populates the + `space `__ + ``name``. + fallback_text (str): + A plain-text description of the message's + cards, used when the actual cards can't be + displayed—for example, mobile notifications. + action_response (google.apps.chat_v1.types.ActionResponse): + Input only. Parameters that a Chat app can + use to configure how its response is posted. + argument_text (str): + Output only. Plain-text body of the message + with all Chat app mentions stripped out. + slash_command (google.apps.chat_v1.types.SlashCommand): + Output only. Slash command information, if + applicable. + attachment (MutableSequence[google.apps.chat_v1.types.Attachment]): + User-uploaded attachment. + matched_url (google.apps.chat_v1.types.MatchedUrl): + Output only. A URL in ``spaces.messages.text`` that matches + a link preview pattern. For more information, see `Preview + links `__. + thread_reply (bool): + Output only. When ``true``, the message is a response in a + reply thread. When ``false``, the message is visible in the + space's top-level conversation as either the first message + of a thread or a message with no threaded replies. + + If the space doesn't support reply in threads, this field is + always ``false``. + client_assigned_message_id (str): + Optional. A custom ID for the message. You can use field to + identify a message, or to get, delete, or update a message. + To set a custom ID, specify the + ```messageId`` `__ + field when you create the message. For details, see `Name a + message `__. + emoji_reaction_summaries (MutableSequence[google.apps.chat_v1.types.EmojiReactionSummary]): + Output only. The list of emoji reaction + summaries on the message. + private_message_viewer (google.apps.chat_v1.types.User): + Immutable. Input for creating a message, otherwise output + only. The user that can view the message. When set, the + message is private and only visible to the specified user + and the Chat app. Link previews and attachments aren't + supported for private messages. + + Only Chat apps can send private messages. If your Chat app + `authenticates as a + user `__ + to send a message, the message can't be private and must + omit this field. + + For details, see `Send private messages to Google Chat + users `__. + deletion_metadata (google.apps.chat_v1.types.DeletionMetadata): + Output only. Information about a deleted message. A message + is deleted when ``delete_time`` is set. + quoted_message_metadata (google.apps.chat_v1.types.QuotedMessageMetadata): + Output only. Information about a message + that's quoted by a Google Chat user in a space. + Google Chat users can quote a message to reply + to it. + attached_gifs (MutableSequence[google.apps.chat_v1.types.AttachedGif]): + Output only. GIF images that are attached to + the message. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + sender: user.User = proto.Field( + proto.MESSAGE, + number=2, + message=user.User, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + last_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=23, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=26, + message=timestamp_pb2.Timestamp, + ) + text: str = proto.Field( + proto.STRING, + number=4, + ) + formatted_text: str = proto.Field( + proto.STRING, + number=43, + ) + cards: MutableSequence[ + contextual_addon.ContextualAddOnMarkup.Card + ] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=contextual_addon.ContextualAddOnMarkup.Card, + ) + cards_v2: MutableSequence["CardWithId"] = proto.RepeatedField( + proto.MESSAGE, + number=22, + message="CardWithId", + ) + annotations: MutableSequence[annotation.Annotation] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=annotation.Annotation, + ) + thread: "Thread" = proto.Field( + proto.MESSAGE, + number=11, + message="Thread", + ) + space: gc_space.Space = proto.Field( + proto.MESSAGE, + number=12, + message=gc_space.Space, + ) + fallback_text: str = proto.Field( + proto.STRING, + number=13, + ) + action_response: "ActionResponse" = proto.Field( + proto.MESSAGE, + number=14, + message="ActionResponse", + ) + argument_text: str = proto.Field( + proto.STRING, + number=15, + ) + slash_command: gc_slash_command.SlashCommand = proto.Field( + proto.MESSAGE, + number=17, + message=gc_slash_command.SlashCommand, + ) + attachment: MutableSequence[gc_attachment.Attachment] = proto.RepeatedField( + proto.MESSAGE, + number=18, + message=gc_attachment.Attachment, + ) + matched_url: gc_matched_url.MatchedUrl = proto.Field( + proto.MESSAGE, + number=20, + message=gc_matched_url.MatchedUrl, + ) + thread_reply: bool = proto.Field( + proto.BOOL, + number=25, + ) + client_assigned_message_id: str = proto.Field( + proto.STRING, + number=32, + ) + emoji_reaction_summaries: MutableSequence[ + reaction.EmojiReactionSummary + ] = proto.RepeatedField( + proto.MESSAGE, + number=33, + message=reaction.EmojiReactionSummary, + ) + private_message_viewer: user.User = proto.Field( + proto.MESSAGE, + number=36, + message=user.User, + ) + deletion_metadata: gc_deletion_metadata.DeletionMetadata = proto.Field( + proto.MESSAGE, + number=38, + message=gc_deletion_metadata.DeletionMetadata, + ) + quoted_message_metadata: "QuotedMessageMetadata" = proto.Field( + proto.MESSAGE, + number=39, + message="QuotedMessageMetadata", + ) + attached_gifs: MutableSequence["AttachedGif"] = proto.RepeatedField( + proto.MESSAGE, + number=42, + message="AttachedGif", + ) + + +class AttachedGif(proto.Message): + r"""A GIF image that's specified by a URL. + + Attributes: + uri (str): + Output only. The URL that hosts the GIF + image. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class QuotedMessageMetadata(proto.Message): + r"""Information about a quoted message. + + Attributes: + name (str): + Output only. Resource name of the quoted message. + + Format: ``spaces/{space}/messages/{message}`` + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the quoted + message was created or when the quoted message + was last updated. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + last_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class Thread(proto.Message): + r"""A thread in a Google Chat space. For example usage, see `Start or + reply to a message + thread `__. + + If you specify a thread when creating a message, you can set the + ```messageReplyOption`` `__ + field to determine what happens if no matching thread is found. + + Attributes: + name (str): + Output only. Resource name of the thread. + + Example: ``spaces/{space}/threads/{thread}`` + thread_key (str): + Optional. Input for creating or updating a thread. + Otherwise, output only. ID for the thread. Supports up to + 4000 characters. + + This ID is unique to the Chat app that sets it. For example, + if multiple Chat apps create a message using the same thread + key, the messages are posted in different threads. To reply + in a thread created by a person or another Chat app, specify + the thread ``name`` field instead. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + thread_key: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ActionResponse(proto.Message): + r"""Parameters that a Chat app can use to configure how its + response is posted. + + Attributes: + type_ (google.apps.chat_v1.types.ActionResponse.ResponseType): + Input only. The type of Chat app response. + url (str): + Input only. URL for users to authenticate or configure. + (Only for ``REQUEST_CONFIG`` response types.) + dialog_action (google.apps.chat_v1.types.DialogAction): + Input only. A response to an interaction event related to a + `dialog `__. + Must be accompanied by ``ResponseType.Dialog``. + updated_widget (google.apps.chat_v1.types.ActionResponse.UpdatedWidget): + Input only. The response of the updated + widget. + """ + + class ResponseType(proto.Enum): + r"""The type of Chat app response. + + Values: + TYPE_UNSPECIFIED (0): + Default type that's handled as ``NEW_MESSAGE``. + NEW_MESSAGE (1): + Post as a new message in the topic. + UPDATE_MESSAGE (2): + Update the Chat app's message. This is only permitted on a + ``CARD_CLICKED`` event where the message sender type is + ``BOT``. + UPDATE_USER_MESSAGE_CARDS (6): + Update the cards on a user's message. This is only permitted + as a response to a ``MESSAGE`` event with a matched url, or + a ``CARD_CLICKED`` event where the message sender type is + ``HUMAN``. Text is ignored. + REQUEST_CONFIG (3): + Privately ask the user for additional + authentication or configuration. + DIALOG (4): + Presents a + `dialog `__. + UPDATE_WIDGET (7): + Widget text autocomplete options query. + """ + TYPE_UNSPECIFIED = 0 + NEW_MESSAGE = 1 + UPDATE_MESSAGE = 2 + UPDATE_USER_MESSAGE_CARDS = 6 + REQUEST_CONFIG = 3 + DIALOG = 4 + UPDATE_WIDGET = 7 + + class SelectionItems(proto.Message): + r"""List of widget autocomplete results. + + Attributes: + items (MutableSequence[google.apps.card_v1.types.SelectionInput.SelectionItem]): + An array of the SelectionItem objects. + """ + + items: MutableSequence[ + gac_card.SelectionInput.SelectionItem + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gac_card.SelectionInput.SelectionItem, + ) + + class UpdatedWidget(proto.Message): + r"""The response of the updated widget. + Used to provide autocomplete options for a widget. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + suggestions (google.apps.chat_v1.types.ActionResponse.SelectionItems): + List of widget autocomplete results + + This field is a member of `oneof`_ ``updated_widget``. + widget (str): + The ID of the updated widget. The ID must + match the one for the widget that triggered the + update request. + """ + + suggestions: "ActionResponse.SelectionItems" = proto.Field( + proto.MESSAGE, + number=1, + oneof="updated_widget", + message="ActionResponse.SelectionItems", + ) + widget: str = proto.Field( + proto.STRING, + number=2, + ) + + type_: ResponseType = proto.Field( + proto.ENUM, + number=1, + enum=ResponseType, + ) + url: str = proto.Field( + proto.STRING, + number=2, + ) + dialog_action: "DialogAction" = proto.Field( + proto.MESSAGE, + number=3, + message="DialogAction", + ) + updated_widget: UpdatedWidget = proto.Field( + proto.MESSAGE, + number=4, + message=UpdatedWidget, + ) + + +class GetMessageRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. Resource name of the message. + + Format: ``spaces/{space}/messages/{message}`` + + If you've set a custom ID for your message, you can use the + value from the ``clientAssignedMessageId`` field for + ``{message}``. For details, see [Name a message] + (https://developers.google.com/chat/api/guides/v1/messages/create#name_a_created_message). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteMessageRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. Resource name of the message. + + Format: ``spaces/{space}/messages/{message}`` + + If you've set a custom ID for your message, you can use the + value from the ``clientAssignedMessageId`` field for + ``{message}``. For details, see [Name a message] + (https://developers.google.com/chat/api/guides/v1/messages/create#name_a_created_message). + force (bool): + When ``true``, deleting a message also deletes its threaded + replies. When ``false``, if a message has threaded replies, + deletion fails. + + Only applies when `authenticating as a + user `__. + Has no effect when [authenticating as a Chat app] + (https://developers.google.com/chat/api/guides/auth/service-accounts). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class UpdateMessageRequest(proto.Message): + r""" + + Attributes: + message (google.apps.chat_v1.types.Message): + Required. Message with fields updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The field paths to update. Separate multiple + values with commas or use ``*`` to update all field paths. + + Currently supported field paths: + + - ``text`` + + - ``attachment`` + + - ``cards`` (Requires `app + authentication `__.) + + - ``cards_v2`` (Requires `app + authentication `__.) + + - Developer Preview: ``accessory_widgets`` (Requires `app + authentication `__.) + allow_missing (bool): + Optional. If ``true`` and the message isn't found, a new + message is created and ``updateMask`` is ignored. The + specified message ID must be + `client-assigned `__ + or the request fails. + """ + + message: "Message" = proto.Field( + proto.MESSAGE, + number=1, + message="Message", + ) + 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=4, + ) + + +class CreateMessageRequest(proto.Message): + r"""Creates a message. + + Attributes: + parent (str): + Required. The resource name of the space in which to create + a message. + + Format: ``spaces/{space}`` + message (google.apps.chat_v1.types.Message): + Required. Message body. + thread_key (str): + Optional. Deprecated: Use + [thread.thread_key][google.chat.v1.Thread.thread_key] + instead. ID for the thread. Supports up to 4000 characters. + To start or add to a thread, create a message and specify a + ``threadKey`` or the + [thread.name][google.chat.v1.Thread.name]. For example + usage, see `Start or reply to a message + thread `__. + request_id (str): + Optional. A unique request ID for this + message. Specifying an existing request ID + returns the message created with that ID instead + of creating a new message. + message_reply_option (google.apps.chat_v1.types.CreateMessageRequest.MessageReplyOption): + Optional. Specifies whether a message starts + a thread or replies to one. Only supported in + named spaces. + message_id (str): + Optional. A custom ID for a message. Lets Chat apps get, + update, or delete a message without needing to store the + system-assigned ID in the message's resource name + (represented in the message ``name`` field). + + The value for this field must meet the following + requirements: + + - Begins with ``client-``. For example, + ``client-custom-name`` is a valid custom ID, but + ``custom-name`` is not. + - Contains up to 63 characters and only lowercase letters, + numbers, and hyphens. + - Is unique within a space. A Chat app can't use the same + custom ID for different messages. + + For details, see `Name a + message `__. + """ + + class MessageReplyOption(proto.Enum): + r"""Specifies how to reply to a message. + More states might be added in the future. + + Values: + MESSAGE_REPLY_OPTION_UNSPECIFIED (0): + Default. Starts a new thread. Using this option ignores any + [thread ID][google.chat.v1.Thread.name] or + [``thread_key``][google.chat.v1.Thread.thread_key] that's + included. + REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD (1): + Creates the message as a reply to the thread specified by + [thread ID][google.chat.v1.Thread.name] or + [``thread_key``][google.chat.v1.Thread.thread_key]. If it + fails, the message starts a new thread instead. + REPLY_MESSAGE_OR_FAIL (2): + Creates the message as a reply to the thread specified by + [thread ID][google.chat.v1.Thread.name] or + [``thread_key``][google.chat.v1.Thread.thread_key]. If a new + ``thread_key`` is used, a new thread is created. If the + message creation fails, a ``NOT_FOUND`` error is returned + instead. + """ + MESSAGE_REPLY_OPTION_UNSPECIFIED = 0 + REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD = 1 + REPLY_MESSAGE_OR_FAIL = 2 + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + message: "Message" = proto.Field( + proto.MESSAGE, + number=4, + message="Message", + ) + thread_key: str = proto.Field( + proto.STRING, + number=6, + ) + request_id: str = proto.Field( + proto.STRING, + number=7, + ) + message_reply_option: MessageReplyOption = proto.Field( + proto.ENUM, + number=8, + enum=MessageReplyOption, + ) + message_id: str = proto.Field( + proto.STRING, + number=9, + ) + + +class ListMessagesRequest(proto.Message): + r"""Lists messages in the specified space, that the user is a + member of. + + Attributes: + parent (str): + Required. The resource name of the space to list messages + from. + + Format: ``spaces/{space}`` + page_size (int): + The maximum number of messages returned. The service might + return fewer messages than this value. + + If unspecified, at most 25 are returned. + + The maximum value is 1,000. If you use a value more than + 1,000, it's automatically changed to 1,000. + + Negative values return an ``INVALID_ARGUMENT`` error. + page_token (str): + Optional, if resuming from a previous query. + + A page token received from a previous list + messages call. Provide this parameter to + retrieve the subsequent page. + + When paginating, all other parameters provided + should match the call that provided the page + token. Passing different values to the other + parameters might lead to unexpected results. + filter (str): + A query filter. + + You can filter messages by date (``create_time``) and thread + (``thread.name``). + + To filter messages by the date they were created, specify + the ``create_time`` with a timestamp in + `RFC-3339 `__ format + and double quotation marks. For example, + ``"2023-04-21T11:30:00-04:00"``. You can use the greater + than operator ``>`` to list messages that were created after + a timestamp, or the less than operator ``<`` to list + messages that were created before a timestamp. To filter + messages within a time interval, use the ``AND`` operator + between two timestamps. + + To filter by thread, specify the ``thread.name``, formatted + as ``spaces/{space}/threads/{thread}``. You can only specify + one ``thread.name`` per query. + + To filter by both thread and date, use the ``AND`` operator + in your query. + + For example, the following queries are valid: + + :: + + create_time > "2012-04-21T11:30:00-04:00" + + create_time > "2012-04-21T11:30:00-04:00" AND + thread.name = spaces/AAAAAAAAAAA/threads/123 + + create_time > "2012-04-21T11:30:00+00:00" AND + + create_time < "2013-01-01T00:00:00+00:00" AND + thread.name = spaces/AAAAAAAAAAA/threads/123 + + thread.name = spaces/AAAAAAAAAAA/threads/123 + + Invalid queries are rejected by the server with an + ``INVALID_ARGUMENT`` error. + order_by (str): + Optional, if resuming from a previous query. + + How the list of messages is ordered. Specify a value to + order by an ordering operation. Valid ordering operation + values are as follows: + + - ``ASC`` for ascending. + + - ``DESC`` for descending. + + The default ordering is ``create_time ASC``. + show_deleted (bool): + Whether to include deleted messages. Deleted + messages include deleted time and metadata about + their deletion, but message content is + unavailable. + """ + + 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, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class ListMessagesResponse(proto.Message): + r""" + + Attributes: + messages (MutableSequence[google.apps.chat_v1.types.Message]): + List of messages. + next_page_token (str): + You can send a token as ``pageToken`` to retrieve the next + page of results. If empty, there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + messages: MutableSequence["Message"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Message", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DialogAction(proto.Message): + r"""Contains a + `dialog `__ and + request status code. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + dialog (google.apps.chat_v1.types.Dialog): + Input only. + `Dialog `__ + for the request. + + This field is a member of `oneof`_ ``action``. + action_status (google.apps.chat_v1.types.ActionStatus): + Input only. Status for a request to either invoke or submit + a + `dialog `__. + Displays a status and message to users, if necessary. For + example, in case of an error or success. + """ + + dialog: "Dialog" = proto.Field( + proto.MESSAGE, + number=1, + oneof="action", + message="Dialog", + ) + action_status: gc_action_status.ActionStatus = proto.Field( + proto.MESSAGE, + number=2, + message=gc_action_status.ActionStatus, + ) + + +class Dialog(proto.Message): + r"""Wrapper around the card body of the dialog. + + Attributes: + body (google.apps.card_v1.types.Card): + Input only. Body of the dialog, which is rendered in a + modal. Google Chat apps don't support the following card + entities: ``DateTimePicker``, ``OnChangeAction``. + """ + + body: gac_card.Card = proto.Field( + proto.MESSAGE, + number=1, + message=gac_card.Card, + ) + + +class CardWithId(proto.Message): + r"""A + `card `__ + in a Google Chat message. + + Only Chat apps can create cards. If your Chat app `authenticates as + a + user `__, + the message can't contain cards. + + `Card builder `__ + + Attributes: + card_id (str): + Required if the message contains multiple + cards. A unique identifier for a card in a + message. + card (google.apps.card_v1.types.Card): + A card. Maximum size is 32 KB. + """ + + card_id: str = proto.Field( + proto.STRING, + number=1, + ) + card: gac_card.Card = proto.Field( + proto.MESSAGE, + number=2, + message=gac_card.Card, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/reaction.py b/packages/google-apps-chat/google/apps/chat_v1/types/reaction.py new file mode 100644 index 000000000000..bc02c2be9c85 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/reaction.py @@ -0,0 +1,310 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 + +from google.apps.chat_v1.types import user as gc_user + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "Reaction", + "Emoji", + "CustomEmoji", + "EmojiReactionSummary", + "CreateReactionRequest", + "ListReactionsRequest", + "ListReactionsResponse", + "DeleteReactionRequest", + }, +) + + +class Reaction(proto.Message): + r"""A reaction to a message. + + Attributes: + name (str): + The resource name of the reaction. + + Format: + ``spaces/{space}/messages/{message}/reactions/{reaction}`` + user (google.apps.chat_v1.types.User): + Output only. The user who created the + reaction. + emoji (google.apps.chat_v1.types.Emoji): + The emoji used in the reaction. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + user: gc_user.User = proto.Field( + proto.MESSAGE, + number=2, + message=gc_user.User, + ) + emoji: "Emoji" = proto.Field( + proto.MESSAGE, + number=3, + message="Emoji", + ) + + +class Emoji(proto.Message): + r"""An emoji that is used as a reaction to a message. + + 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: + unicode (str): + A basic emoji represented by a unicode + string. + + This field is a member of `oneof`_ ``content``. + custom_emoji (google.apps.chat_v1.types.CustomEmoji): + Output only. A custom emoji. + + This field is a member of `oneof`_ ``content``. + """ + + unicode: str = proto.Field( + proto.STRING, + number=1, + oneof="content", + ) + custom_emoji: "CustomEmoji" = proto.Field( + proto.MESSAGE, + number=2, + oneof="content", + message="CustomEmoji", + ) + + +class CustomEmoji(proto.Message): + r"""Represents a custom emoji. + + Attributes: + uid (str): + Unique key for the custom emoji resource. + """ + + uid: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EmojiReactionSummary(proto.Message): + r"""The number of people who reacted to a message with a specific + emoji. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + emoji (google.apps.chat_v1.types.Emoji): + Emoji associated with the reactions. + reaction_count (int): + The total number of reactions using the + associated emoji. + + This field is a member of `oneof`_ ``_reaction_count``. + """ + + emoji: "Emoji" = proto.Field( + proto.MESSAGE, + number=1, + message="Emoji", + ) + reaction_count: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + +class CreateReactionRequest(proto.Message): + r"""Creates a reaction to a message. + + Attributes: + parent (str): + Required. The message where the reaction is created. + + Format: ``spaces/{space}/messages/{message}`` + reaction (google.apps.chat_v1.types.Reaction): + Required. The reaction to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + reaction: "Reaction" = proto.Field( + proto.MESSAGE, + number=2, + message="Reaction", + ) + + +class ListReactionsRequest(proto.Message): + r"""Lists reactions to a message. + + Attributes: + parent (str): + Required. The message users reacted to. + + Format: ``spaces/{space}/messages/{message}`` + page_size (int): + Optional. The maximum number of reactions + returned. The service can return fewer reactions + than this value. If unspecified, the default + value is 25. The maximum value is 200; values + above 200 are changed to 200. + page_token (str): + Optional. (If resuming from a previous + query.) + A page token received from a previous list + reactions call. Provide this to retrieve the + subsequent page. + + When paginating, the filter value should match + the call that provided the page token. Passing a + different value might lead to unexpected + results. + filter (str): + Optional. A query filter. + + You can filter reactions by + `emoji `__ + (either ``emoji.unicode`` or ``emoji.custom_emoji.uid``) and + `user `__ + (``user.name``). + + To filter reactions for multiple emojis or users, join + similar fields with the ``OR`` operator, such as + ``emoji.unicode = "🙂" OR emoji.unicode = "👍"`` and + ``user.name = "users/AAAAAA" OR user.name = "users/BBBBBB"``. + + To filter reactions by emoji and user, use the ``AND`` + operator, such as + ``emoji.unicode = "🙂" AND user.name = "users/AAAAAA"``. + + If your query uses both ``AND`` and ``OR``, group them with + parentheses. + + For example, the following queries are valid: + + :: + + user.name = "users/{user}" + emoji.unicode = "🙂" + emoji.custom_emoji.uid = "{uid}" + emoji.unicode = "🙂" OR emoji.unicode = "👍" + emoji.unicode = "🙂" OR emoji.custom_emoji.uid = "{uid}" + emoji.unicode = "🙂" AND user.name = "users/{user}" + (emoji.unicode = "🙂" OR emoji.custom_emoji.uid = "{uid}") + AND user.name = "users/{user}" + + The following queries are invalid: + + :: + + emoji.unicode = "🙂" AND emoji.unicode = "👍" + emoji.unicode = "🙂" AND emoji.custom_emoji.uid = "{uid}" + emoji.unicode = "🙂" OR user.name = "users/{user}" + emoji.unicode = "🙂" OR emoji.custom_emoji.uid = "{uid}" OR + user.name = "users/{user}" + emoji.unicode = "🙂" OR emoji.custom_emoji.uid = "{uid}" + AND user.name = "users/{user}" + + Invalid queries are rejected by the server with an + ``INVALID_ARGUMENT`` error. + """ + + 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, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListReactionsResponse(proto.Message): + r""" + + Attributes: + reactions (MutableSequence[google.apps.chat_v1.types.Reaction]): + List of reactions in the requested (or first) + page. + next_page_token (str): + Continuation token to retrieve the next page + of results. It's empty for the last page of + results. + """ + + @property + def raw_page(self): + return self + + reactions: MutableSequence["Reaction"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Reaction", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteReactionRequest(proto.Message): + r"""Deletes a reaction to a message. + + Attributes: + name (str): + Required. Name of the reaction to delete. + + Format: + ``spaces/{space}/messages/{message}/reactions/{reaction}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/slash_command.py b/packages/google-apps-chat/google/apps/chat_v1/types/slash_command.py new file mode 100644 index 000000000000..0921360eea92 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/slash_command.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.chat.v1", + manifest={ + "SlashCommand", + }, +) + + +class SlashCommand(proto.Message): + r"""A `slash + command `__ + in Google Chat. + + Attributes: + command_id (int): + The ID of the slash command invoked. + """ + + command_id: int = proto.Field( + proto.INT64, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/space.py b/packages/google-apps-chat/google/apps/chat_v1/types/space.py new file mode 100644 index 000000000000..271183fa8e06 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/space.py @@ -0,0 +1,563 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.apps.chat_v1.types import history_state + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "Space", + "CreateSpaceRequest", + "ListSpacesRequest", + "ListSpacesResponse", + "GetSpaceRequest", + "FindDirectMessageRequest", + "UpdateSpaceRequest", + "DeleteSpaceRequest", + "CompleteImportSpaceRequest", + "CompleteImportSpaceResponse", + }, +) + + +class Space(proto.Message): + r"""A space in Google Chat. Spaces are conversations between two + or more users or 1:1 messages between a user and a Chat app. + + Attributes: + name (str): + Resource name of the space. + + Format: ``spaces/{space}`` + type_ (google.apps.chat_v1.types.Space.Type): + Output only. Deprecated: Use ``space_type`` instead. The + type of a space. + space_type (google.apps.chat_v1.types.Space.SpaceType): + The type of space. Required when creating a + space or updating the space type of a space. + Output only for other usage. + single_user_bot_dm (bool): + Optional. Whether the space is a DM between a + Chat app and a single human. + threaded (bool): + Output only. Deprecated: Use ``spaceThreadingState`` + instead. Whether messages are threaded in this space. + display_name (str): + The space's display name. Required when `creating a + space `__. + If you receive the error message ``ALREADY_EXISTS`` when + creating a space or updating the ``displayName``, try a + different ``displayName``. An existing space within the + Google Workspace organization might already use this display + name. + + For direct messages, this field might be empty. + + Supports up to 128 characters. + external_user_allowed (bool): + Immutable. Whether this space permits any Google Chat user + as a member. Input when creating a space in a Google + Workspace organization. Omit this field when creating spaces + in the following conditions: + + - The authenticated user uses a Google Account. By default, + the space permits any Google Chat user. + + - The space is used to [import data to Google Chat] + (https://developers.google.com/chat/api/guides/import-data-overview). + Import mode spaces must only permit members from the same + Google Workspace organization. + + For existing spaces, this field is output only. + space_threading_state (google.apps.chat_v1.types.Space.SpaceThreadingState): + Output only. The threading state in the Chat + space. + space_details (google.apps.chat_v1.types.Space.SpaceDetails): + Details about the space including description + and rules. + space_history_state (google.apps.chat_v1.types.HistoryState): + The message history state for messages and + threads in this space. + import_mode (bool): + Optional. Whether this space is created in ``Import Mode`` + as part of a data migration into Google Workspace. While + spaces are being imported, they aren't visible to users + until the import is complete. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Immutable. For spaces created in Chat, the time + the space was created. This field is output only, except + when used in import mode spaces. + + For import mode spaces, set this field to the historical + timestamp at which the space was created in the source in + order to preserve the original creation time. + + Only populated in the output when ``spaceType`` is + ``GROUP_CHAT`` or ``SPACE``. + admin_installed (bool): + Output only. Whether the Chat app was + installed by a Google Workspace administrator. + Administrators can install a Chat app for their + domain, organizational unit, or a group of + users. + + Administrators can only install Chat apps for + direct messaging between users and the app. To + support admin install, your app must feature + direct messaging. + """ + + class Type(proto.Enum): + r"""Deprecated: Use ``SpaceType`` instead. + + Values: + TYPE_UNSPECIFIED (0): + No description available. + ROOM (1): + Conversations between two or more humans. + DM (2): + 1:1 Direct Message between a human and a Chat + app, where all messages are flat. Note that this + doesn't include direct messages between two + humans. + """ + TYPE_UNSPECIFIED = 0 + ROOM = 1 + DM = 2 + + class SpaceType(proto.Enum): + r"""The type of space. Required when creating or updating a + space. Output only for other usage. + + Values: + SPACE_TYPE_UNSPECIFIED (0): + Reserved. + SPACE (1): + A place where people send messages, share files, and + collaborate. A ``SPACE`` can include Chat apps. + GROUP_CHAT (2): + Group conversations between 3 or more people. A + ``GROUP_CHAT`` can include Chat apps. + DIRECT_MESSAGE (3): + 1:1 messages between two humans or a human + and a Chat app. + """ + SPACE_TYPE_UNSPECIFIED = 0 + SPACE = 1 + GROUP_CHAT = 2 + DIRECT_MESSAGE = 3 + + class SpaceThreadingState(proto.Enum): + r"""Specifies the type of threading state in the Chat space. + + Values: + SPACE_THREADING_STATE_UNSPECIFIED (0): + Reserved. + THREADED_MESSAGES (2): + Named spaces that support message threads. + When users respond to a message, they can reply + in-thread, which keeps their response in the + context of the original message. + GROUPED_MESSAGES (3): + Named spaces where the conversation is + organized by topic. Topics and their replies are + grouped together. + UNTHREADED_MESSAGES (4): + Direct messages (DMs) between two people and + group conversations between 3 or more people. + """ + SPACE_THREADING_STATE_UNSPECIFIED = 0 + THREADED_MESSAGES = 2 + GROUPED_MESSAGES = 3 + UNTHREADED_MESSAGES = 4 + + class SpaceDetails(proto.Message): + r"""Details about the space including description and rules. + + Attributes: + description (str): + Optional. A description of the space. For + example, describe the space's discussion topic, + functional purpose, or participants. + + Supports up to 150 characters. + guidelines (str): + Optional. The space's rules, expectations, + and etiquette. + Supports up to 5,000 characters. + """ + + description: str = proto.Field( + proto.STRING, + number=1, + ) + guidelines: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: Type = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + space_type: SpaceType = proto.Field( + proto.ENUM, + number=10, + enum=SpaceType, + ) + single_user_bot_dm: bool = proto.Field( + proto.BOOL, + number=4, + ) + threaded: bool = proto.Field( + proto.BOOL, + number=5, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + external_user_allowed: bool = proto.Field( + proto.BOOL, + number=8, + ) + space_threading_state: SpaceThreadingState = proto.Field( + proto.ENUM, + number=9, + enum=SpaceThreadingState, + ) + space_details: SpaceDetails = proto.Field( + proto.MESSAGE, + number=11, + message=SpaceDetails, + ) + space_history_state: history_state.HistoryState = proto.Field( + proto.ENUM, + number=13, + enum=history_state.HistoryState, + ) + import_mode: bool = proto.Field( + proto.BOOL, + number=16, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=17, + message=timestamp_pb2.Timestamp, + ) + admin_installed: bool = proto.Field( + proto.BOOL, + number=19, + ) + + +class CreateSpaceRequest(proto.Message): + r""" + + Attributes: + space (google.apps.chat_v1.types.Space): + Required. The ``displayName`` and ``spaceType`` fields must + be populated. Only ``SpaceType.SPACE`` is supported. + + If you receive the error message ``ALREADY_EXISTS`` when + creating a space, try a different ``displayName``. An + existing space within the Google Workspace organization + might already use this display name. + + The space ``name`` is assigned on the server so anything + specified in this field will be ignored. + request_id (str): + Optional. A unique identifier for this + request. A random UUID is recommended. + Specifying an existing request ID returns the + space created with that ID instead of creating a + new space. + Specifying an existing request ID from the same + Chat app with a different authenticated user + returns an error. + """ + + space: "Space" = proto.Field( + proto.MESSAGE, + number=1, + message="Space", + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSpacesRequest(proto.Message): + r"""A request to list the spaces the caller is a member of. + + Attributes: + page_size (int): + Optional. The maximum number of spaces to return. The + service might return fewer than this value. + + If unspecified, at most 100 spaces are returned. + + The maximum value is 1,000. If you use a value more than + 1,000, it's automatically changed to 1,000. + + Negative values return an ``INVALID_ARGUMENT`` error. + page_token (str): + Optional. A page token, received from a + previous list spaces call. Provide this + parameter to retrieve the subsequent page. + + When paginating, the filter value should match + the call that provided the page token. Passing a + different value may lead to unexpected results. + filter (str): + Optional. A query filter. + + You can filter spaces by the space type + (```space_type`` `__). + + To filter by space type, you must specify valid enum value, + such as ``SPACE`` or ``GROUP_CHAT`` (the ``space_type`` + can't be ``SPACE_TYPE_UNSPECIFIED``). To query for multiple + space types, use the ``OR`` operator. + + For example, the following queries are valid: + + :: + + space_type = "SPACE" + spaceType = "GROUP_CHAT" OR spaceType = "DIRECT_MESSAGE" + + Invalid queries are rejected by the server with an + ``INVALID_ARGUMENT`` error. + """ + + page_size: int = proto.Field( + proto.INT32, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSpacesResponse(proto.Message): + r""" + + Attributes: + spaces (MutableSequence[google.apps.chat_v1.types.Space]): + List of spaces in the requested (or first) + page. + next_page_token (str): + You can send a token as ``pageToken`` to retrieve the next + page of results. If empty, there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + spaces: MutableSequence["Space"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Space", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetSpaceRequest(proto.Message): + r"""A request to return a single space. + + Attributes: + name (str): + Required. Resource name of the space, in the form + `spaces/*`. + + Format: ``spaces/{space}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class FindDirectMessageRequest(proto.Message): + r"""A request to get direct message space based on the user + resource. + + Attributes: + name (str): + Required. Resource name of the user to find direct message + with. + + Format: ``users/{user}``, where ``{user}`` is either the + ``id`` for the + `person `__ + from the People API, or the ``id`` for the + `user `__ + in the Directory API. For example, if the People API profile + ID is ``123456789``, you can find a direct message with that + person by using ``users/123456789`` as the ``name``. When + `authenticated as a + user `__, + you can use the email as an alias for ``{user}``. For + example, ``users/example@gmail.com`` where + ``example@gmail.com`` is the email of the Google Chat user. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateSpaceRequest(proto.Message): + r"""A request to update a single space. + + Attributes: + space (google.apps.chat_v1.types.Space): + Required. Space with fields to be updated. ``Space.name`` + must be populated in the form of ``spaces/{space}``. Only + fields specified by ``update_mask`` are updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The updated field paths, comma separated if there + are multiple. + + Currently supported field paths: + + - ``display_name`` (Only supports changing the display name + of a space with the ``SPACE`` type, or when also + including the ``space_type`` mask to change a + ``GROUP_CHAT`` space type to ``SPACE``. Trying to update + the display name of a ``GROUP_CHAT`` or a + ``DIRECT_MESSAGE`` space results in an invalid argument + error. If you receive the error message + ``ALREADY_EXISTS`` when updating the ``displayName``, try + a different ``displayName``. An existing space within the + Google Workspace organization might already use this + display name.) + + - ``space_type`` (Only supports changing a ``GROUP_CHAT`` + space type to ``SPACE``. Include ``display_name`` + together with ``space_type`` in the update mask and + ensure that the specified space has a non-empty display + name and the ``SPACE`` space type. Including the + ``space_type`` mask and the ``SPACE`` type in the + specified space when updating the display name is + optional if the existing space already has the ``SPACE`` + type. Trying to update the space type in other ways + results in an invalid argument error). + + - ``space_details`` + + - ``space_history_state`` (Supports `turning history on or + off for the + space `__ + if `the organization allows users to change their history + setting `__. + Warning: mutually exclusive with all other field paths.) + + - Developer Preview: ``access_settings.audience`` (Supports + changing the `access + setting `__ + of a space. If no audience is specified in the access + setting, the space's access setting is updated to + restricted. Warning: mutually exclusive with all other + field paths.) + """ + + space: "Space" = proto.Field( + proto.MESSAGE, + number=1, + message="Space", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteSpaceRequest(proto.Message): + r"""Request for deleting a space. + + Attributes: + name (str): + Required. Resource name of the space to delete. + + Format: ``spaces/{space}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CompleteImportSpaceRequest(proto.Message): + r"""Request message for completing the import process for a + space. + + Attributes: + name (str): + Required. Resource name of the import mode space. + + Format: ``spaces/{space}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CompleteImportSpaceResponse(proto.Message): + r""" + + Attributes: + space (google.apps.chat_v1.types.Space): + The import mode space. + """ + + space: "Space" = proto.Field( + proto.MESSAGE, + number=1, + message="Space", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/space_setup.py b/packages/google-apps-chat/google/apps/chat_v1/types/space_setup.py new file mode 100644 index 000000000000..a064144ea378 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/space_setup.py @@ -0,0 +1,120 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 + +from google.apps.chat_v1.types import membership +from google.apps.chat_v1.types import space as gc_space + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "SetUpSpaceRequest", + }, +) + + +class SetUpSpaceRequest(proto.Message): + r""" + + Attributes: + space (google.apps.chat_v1.types.Space): + Required. The ``Space.spaceType`` field is required. + + To create a space, set ``Space.spaceType`` to ``SPACE`` and + set ``Space.displayName``. If you receive the error message + ``ALREADY_EXISTS`` when setting up a space, try a different + ``displayName``. An existing space within the Google + Workspace organization might already use this display name. + + To create a group chat, set ``Space.spaceType`` to + ``GROUP_CHAT``. Don't set ``Space.displayName``. + + To create a 1:1 conversation between humans, set + ``Space.spaceType`` to ``DIRECT_MESSAGE`` and set + ``Space.singleUserBotDm`` to ``false``. Don't set + ``Space.displayName`` or ``Space.spaceDetails``. + + To create an 1:1 conversation between a human and the + calling Chat app, set ``Space.spaceType`` to + ``DIRECT_MESSAGE`` and ``Space.singleUserBotDm`` to + ``true``. Don't set ``Space.displayName`` or + ``Space.spaceDetails``. + + If a ``DIRECT_MESSAGE`` space already exists, that space is + returned instead of creating a new space. + request_id (str): + Optional. A unique identifier for this + request. A random UUID is recommended. + Specifying an existing request ID returns the + space created with that ID instead of creating a + new space. + Specifying an existing request ID from the same + Chat app with a different authenticated user + returns an error. + memberships (MutableSequence[google.apps.chat_v1.types.Membership]): + Optional. The Google Chat users to invite to join the space. + Omit the calling user, as they are added automatically. + + The set currently allows up to 20 memberships (in addition + to the caller). + + The ``Membership.member`` field must contain a ``user`` with + ``name`` populated (format: ``users/{user}``) and ``type`` + set to ``User.Type.HUMAN``. You can only add human users + when setting up a space (adding Chat apps is only supported + for direct message setup with the calling app). You can also + add members using the user's email as an alias for {user}. + For example, the ``user.name`` can be + ``users/example@gmail.com``." To invite Gmail users or users + from external Google Workspace domains, user's email must be + used for ``{user}``. + + Optional when setting ``Space.spaceType`` to ``SPACE``. + + Required when setting ``Space.spaceType`` to ``GROUP_CHAT``, + along with at least two memberships. + + Required when setting ``Space.spaceType`` to + ``DIRECT_MESSAGE`` with a human user, along with exactly one + membership. + + Must be empty when creating a 1:1 conversation between a + human and the calling Chat app (when setting + ``Space.spaceType`` to ``DIRECT_MESSAGE`` and + ``Space.singleUserBotDm`` to ``true``). + """ + + space: gc_space.Space = proto.Field( + proto.MESSAGE, + number=1, + message=gc_space.Space, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + memberships: MutableSequence[membership.Membership] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=membership.Membership, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/user.py b/packages/google-apps-chat/google/apps/chat_v1/types/user.py new file mode 100644 index 000000000000..58c35f7e7b8d --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/user.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.chat.v1", + manifest={ + "User", + }, +) + + +class User(proto.Message): + r"""A user in Google Chat. When returned as an output from a request, if + your Chat app `authenticates as a + user `__, + the output for a ``User`` resource only populates the user's + ``name`` and ``type``. + + Attributes: + name (str): + Resource name for a Google Chat [user][google.chat.v1.User]. + + Format: ``users/{user}``. ``users/app`` can be used as an + alias for the calling app + [bot][google.chat.v1.User.Type.BOT] user. + + For [human users][google.chat.v1.User.Type.HUMAN], + ``{user}`` is the same user identifier as: + + - the ``id`` for the + `Person `__ + in the People API. For example, ``users/123456789`` in + Chat API represents the same person as the ``123456789`` + Person profile ID in People API. + + - the ``id`` for a + `user `__ + in the Admin SDK Directory API. + + - the user's email address can be used as an alias for + ``{user}`` in API requests. For example, if the People + API Person profile ID for ``user@example.com`` is + ``123456789``, you can use ``users/user@example.com`` as + an alias to reference ``users/123456789``. Only the + canonical resource name (for example ``users/123456789``) + will be returned from the API. + display_name (str): + Output only. The user's display name. + domain_id (str): + Unique identifier of the user's Google + Workspace domain. + type_ (google.apps.chat_v1.types.User.Type): + User type. + is_anonymous (bool): + Output only. When ``true``, the user is deleted or their + profile is not visible. + """ + + class Type(proto.Enum): + r""" + + Values: + TYPE_UNSPECIFIED (0): + Default value for the enum. DO NOT USE. + HUMAN (1): + Human user. + BOT (2): + Chat app user. + """ + TYPE_UNSPECIFIED = 0 + HUMAN = 1 + BOT = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + domain_id: str = proto.Field( + proto.STRING, + number=6, + ) + type_: Type = proto.Field( + proto.ENUM, + number=5, + enum=Type, + ) + is_anonymous: bool = proto.Field( + proto.BOOL, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/widgets.py b/packages/google-apps-chat/google/apps/chat_v1/types/widgets.py new file mode 100644 index 000000000000..b5d2114224c0 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/widgets.py @@ -0,0 +1,529 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.chat.v1", + manifest={ + "WidgetMarkup", + }, +) + + +class WidgetMarkup(proto.Message): + r"""A widget is a UI element that presents text and images. + + 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: + text_paragraph (google.apps.chat_v1.types.WidgetMarkup.TextParagraph): + Display a text paragraph in this widget. + + This field is a member of `oneof`_ ``data``. + image (google.apps.chat_v1.types.WidgetMarkup.Image): + Display an image in this widget. + + This field is a member of `oneof`_ ``data``. + key_value (google.apps.chat_v1.types.WidgetMarkup.KeyValue): + Display a key value item in this widget. + + This field is a member of `oneof`_ ``data``. + buttons (MutableSequence[google.apps.chat_v1.types.WidgetMarkup.Button]): + A list of buttons. Buttons is also ``oneof data`` and only + one of these fields should be set. + """ + + class Icon(proto.Enum): + r"""The set of supported icons. + + Values: + ICON_UNSPECIFIED (0): + No description available. + AIRPLANE (1): + No description available. + BOOKMARK (26): + No description available. + BUS (25): + No description available. + CAR (9): + No description available. + CLOCK (2): + No description available. + CONFIRMATION_NUMBER_ICON (12): + No description available. + DOLLAR (14): + No description available. + DESCRIPTION (27): + No description available. + EMAIL (10): + No description available. + EVENT_PERFORMER (20): + No description available. + EVENT_SEAT (21): + No description available. + FLIGHT_ARRIVAL (16): + No description available. + FLIGHT_DEPARTURE (15): + No description available. + HOTEL (6): + No description available. + HOTEL_ROOM_TYPE (17): + No description available. + INVITE (19): + No description available. + MAP_PIN (3): + No description available. + MEMBERSHIP (24): + No description available. + MULTIPLE_PEOPLE (18): + No description available. + OFFER (30): + No description available. + PERSON (11): + No description available. + PHONE (13): + No description available. + RESTAURANT_ICON (7): + No description available. + SHOPPING_CART (8): + No description available. + STAR (5): + No description available. + STORE (22): + No description available. + TICKET (4): + No description available. + TRAIN (23): + No description available. + VIDEO_CAMERA (28): + No description available. + VIDEO_PLAY (29): + No description available. + """ + ICON_UNSPECIFIED = 0 + AIRPLANE = 1 + BOOKMARK = 26 + BUS = 25 + CAR = 9 + CLOCK = 2 + CONFIRMATION_NUMBER_ICON = 12 + DOLLAR = 14 + DESCRIPTION = 27 + EMAIL = 10 + EVENT_PERFORMER = 20 + EVENT_SEAT = 21 + FLIGHT_ARRIVAL = 16 + FLIGHT_DEPARTURE = 15 + HOTEL = 6 + HOTEL_ROOM_TYPE = 17 + INVITE = 19 + MAP_PIN = 3 + MEMBERSHIP = 24 + MULTIPLE_PEOPLE = 18 + OFFER = 30 + PERSON = 11 + PHONE = 13 + RESTAURANT_ICON = 7 + SHOPPING_CART = 8 + STAR = 5 + STORE = 22 + TICKET = 4 + TRAIN = 23 + VIDEO_CAMERA = 28 + VIDEO_PLAY = 29 + + class TextParagraph(proto.Message): + r"""A paragraph of text. Formatted text supported. For more information + about formatting text, see `Formatting text in Google Chat + apps `__ + and `Formatting text in Google Workspace + Add-ons `__. + + Attributes: + text (str): + + """ + + text: str = proto.Field( + proto.STRING, + number=1, + ) + + class Button(proto.Message): + r"""A button. Can be a text button or an image button. + + 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: + text_button (google.apps.chat_v1.types.WidgetMarkup.TextButton): + A button with text and ``onclick`` action. + + This field is a member of `oneof`_ ``type``. + image_button (google.apps.chat_v1.types.WidgetMarkup.ImageButton): + A button with image and ``onclick`` action. + + This field is a member of `oneof`_ ``type``. + """ + + text_button: "WidgetMarkup.TextButton" = proto.Field( + proto.MESSAGE, + number=1, + oneof="type", + message="WidgetMarkup.TextButton", + ) + image_button: "WidgetMarkup.ImageButton" = proto.Field( + proto.MESSAGE, + number=2, + oneof="type", + message="WidgetMarkup.ImageButton", + ) + + class TextButton(proto.Message): + r"""A button with text and ``onclick`` action. + + Attributes: + text (str): + The text of the button. + on_click (google.apps.chat_v1.types.WidgetMarkup.OnClick): + The ``onclick`` action of the button. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + ) + on_click: "WidgetMarkup.OnClick" = proto.Field( + proto.MESSAGE, + number=2, + message="WidgetMarkup.OnClick", + ) + + class KeyValue(proto.Message): + r"""A UI element contains a key (label) and a value (content). This + element can also contain some actions such as ``onclick`` button. + + 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: + icon (google.apps.chat_v1.types.WidgetMarkup.Icon): + An enum value that's replaced by the Chat API + with the corresponding icon image. + + This field is a member of `oneof`_ ``icons``. + icon_url (str): + The icon specified by a URL. + + This field is a member of `oneof`_ ``icons``. + top_label (str): + The text of the top label. Formatted text supported. For + more information about formatting text, see `Formatting text + in Google Chat + apps `__ + and `Formatting text in Google Workspace + Add-ons `__. + content (str): + The text of the content. Formatted text supported and always + required. For more information about formatting text, see + `Formatting text in Google Chat + apps `__ + and `Formatting text in Google Workspace + Add-ons `__. + content_multiline (bool): + If the content should be multiline. + bottom_label (str): + The text of the bottom label. Formatted text supported. For + more information about formatting text, see `Formatting text + in Google Chat + apps `__ + and `Formatting text in Google Workspace + Add-ons `__. + on_click (google.apps.chat_v1.types.WidgetMarkup.OnClick): + The ``onclick`` action. Only the top label, bottom label, + and content region are clickable. + button (google.apps.chat_v1.types.WidgetMarkup.Button): + A button that can be clicked to trigger an + action. + + This field is a member of `oneof`_ ``control``. + """ + + icon: "WidgetMarkup.Icon" = proto.Field( + proto.ENUM, + number=1, + oneof="icons", + enum="WidgetMarkup.Icon", + ) + icon_url: str = proto.Field( + proto.STRING, + number=2, + oneof="icons", + ) + top_label: str = proto.Field( + proto.STRING, + number=3, + ) + content: str = proto.Field( + proto.STRING, + number=4, + ) + content_multiline: bool = proto.Field( + proto.BOOL, + number=9, + ) + bottom_label: str = proto.Field( + proto.STRING, + number=5, + ) + on_click: "WidgetMarkup.OnClick" = proto.Field( + proto.MESSAGE, + number=6, + message="WidgetMarkup.OnClick", + ) + button: "WidgetMarkup.Button" = proto.Field( + proto.MESSAGE, + number=7, + oneof="control", + message="WidgetMarkup.Button", + ) + + class Image(proto.Message): + r"""An image that's specified by a URL and can have an ``onclick`` + action. + + Attributes: + image_url (str): + The URL of the image. + on_click (google.apps.chat_v1.types.WidgetMarkup.OnClick): + The ``onclick`` action. + aspect_ratio (float): + The aspect ratio of this image (width and + height). This field lets you reserve the right + height for the image while waiting for it to + load. It's not meant to override the built-in + aspect ratio of the image. If unset, the server + fills it by prefetching the image. + """ + + image_url: str = proto.Field( + proto.STRING, + number=1, + ) + on_click: "WidgetMarkup.OnClick" = proto.Field( + proto.MESSAGE, + number=2, + message="WidgetMarkup.OnClick", + ) + aspect_ratio: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + class ImageButton(proto.Message): + r"""An image button with an ``onclick`` action. + + 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: + icon (google.apps.chat_v1.types.WidgetMarkup.Icon): + The icon specified by an ``enum`` that indices to an icon + provided by Chat API. + + This field is a member of `oneof`_ ``icons``. + icon_url (str): + The icon specified by a URL. + + This field is a member of `oneof`_ ``icons``. + on_click (google.apps.chat_v1.types.WidgetMarkup.OnClick): + The ``onclick`` action. + name (str): + The name of this ``image_button`` that's used for + accessibility. Default value is provided if this name isn't + specified. + """ + + icon: "WidgetMarkup.Icon" = proto.Field( + proto.ENUM, + number=1, + oneof="icons", + enum="WidgetMarkup.Icon", + ) + icon_url: str = proto.Field( + proto.STRING, + number=3, + oneof="icons", + ) + on_click: "WidgetMarkup.OnClick" = proto.Field( + proto.MESSAGE, + number=2, + message="WidgetMarkup.OnClick", + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + + class OnClick(proto.Message): + r"""An ``onclick`` action (for example, open a link). + + 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: + action (google.apps.chat_v1.types.WidgetMarkup.FormAction): + A form action is triggered by this ``onclick`` action if + specified. + + This field is a member of `oneof`_ ``data``. + open_link (google.apps.chat_v1.types.WidgetMarkup.OpenLink): + This ``onclick`` action triggers an open link action if + specified. + + This field is a member of `oneof`_ ``data``. + """ + + action: "WidgetMarkup.FormAction" = proto.Field( + proto.MESSAGE, + number=1, + oneof="data", + message="WidgetMarkup.FormAction", + ) + open_link: "WidgetMarkup.OpenLink" = proto.Field( + proto.MESSAGE, + number=2, + oneof="data", + message="WidgetMarkup.OpenLink", + ) + + class OpenLink(proto.Message): + r"""A link that opens a new window. + + Attributes: + url (str): + The URL to open. + """ + + url: str = proto.Field( + proto.STRING, + number=1, + ) + + class FormAction(proto.Message): + r"""A form action describes the behavior when the form is + submitted. For example, you can invoke Apps Script to handle the + form. + + Attributes: + action_method_name (str): + The method name is used to identify which + part of the form triggered the form submission. + This information is echoed back to the Chat app + as part of the card click event. You can use the + same method name for several elements that + trigger a common behavior. + parameters (MutableSequence[google.apps.chat_v1.types.WidgetMarkup.FormAction.ActionParameter]): + List of action parameters. + """ + + class ActionParameter(proto.Message): + r"""List of string parameters to supply when the action method is + invoked. For example, consider three snooze buttons: snooze now, + snooze one day, snooze next week. You might use + ``action method = snooze()``, passing the snooze type and snooze + time in the list of string parameters. + + Attributes: + key (str): + The name of the parameter for the action + script. + value (str): + The value of the parameter. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + action_method_name: str = proto.Field( + proto.STRING, + number=1, + ) + parameters: MutableSequence[ + "WidgetMarkup.FormAction.ActionParameter" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="WidgetMarkup.FormAction.ActionParameter", + ) + + text_paragraph: TextParagraph = proto.Field( + proto.MESSAGE, + number=1, + oneof="data", + message=TextParagraph, + ) + image: Image = proto.Field( + proto.MESSAGE, + number=2, + oneof="data", + message=Image, + ) + key_value: KeyValue = proto.Field( + proto.MESSAGE, + number=3, + oneof="data", + message=KeyValue, + ) + buttons: MutableSequence[Button] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=Button, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/mypy.ini b/packages/google-apps-chat/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/packages/google-apps-chat/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/packages/google-apps-chat/noxfile.py b/packages/google-apps-chat/noxfile.py new file mode 100644 index 000000000000..1e6cd48d0529 --- /dev/null +++ b/packages/google-apps-chat/noxfile.py @@ -0,0 +1,428 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2023 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 +# +# https://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 by synthtool. DO NOT EDIT! + +from __future__ import absolute_import + +import os +import pathlib +import re +import shutil +from typing import Dict, List +import warnings + +import nox + +BLACK_VERSION = "black[jupyter]==23.7.0" +ISORT_VERSION = "isort==5.11.0" + +LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] + + +DEFAULT_PYTHON_VERSION = "3.10" + +UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "asyncmock", + "pytest", + "pytest-cov", + "pytest-asyncio", +] +UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_DEPENDENCIES: List[str] = [] +UNIT_TEST_EXTRAS: List[str] = [] +UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "pytest", + "google-cloud-testutils", +] +SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_EXTRAS: List[str] = [] +SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +# 'docfx' is excluded since it only needs to run in 'docs-presubmit' +nox.options.sessions = [ + "unit", + "system", + "cover", + "lint", + "lint_setup_py", + "blacken", + "docs", +] + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *LINT_PATHS, + ) + + session.run("flake8", "google", "tests") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def format(session): + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run( + "isort", + "--fss", + *LINT_PATHS, + ) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") + + +def install_unittest_dependencies(session, *constraints): + standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES + session.install(*standard_deps, *constraints) + + if UNIT_TEST_EXTERNAL_DEPENDENCIES: + warnings.warn( + "'unit_test_external_dependencies' is deprecated. Instead, please " + "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", + DeprecationWarning, + ) + session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_LOCAL_DEPENDENCIES: + session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_EXTRAS_BY_PYTHON: + extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif UNIT_TEST_EXTRAS: + extras = UNIT_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +def default(session): + # Install all test dependencies, then install this package in-place. + + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + install_unittest_dependencies(session, "-c", constraints_path) + + # Run py.test against the unit tests. + session.run( + "py.test", + "--quiet", + f"--junitxml=unit_{session.python}_sponge_log.xml", + "--cov=google", + "--cov=tests/unit", + "--cov-append", + "--cov-config=.coveragerc", + "--cov-report=", + "--cov-fail-under=0", + os.path.join("tests", "unit"), + *session.posargs, + ) + + +@nox.session(python=UNIT_TEST_PYTHON_VERSIONS) +def unit(session): + """Run the unit test suite.""" + default(session) + + +def install_systemtest_dependencies(session, *constraints): + # Use pre-release gRPC for system tests. + # Exclude version 1.52.0rc1 which has a known issue. + # See https://github.com/grpc/grpc/issues/32163 + session.install("--pre", "grpcio!=1.52.0rc1") + + session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: + session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_LOCAL_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTRAS_BY_PYTHON: + extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif SYSTEM_TEST_EXTRAS: + extras = SYSTEM_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) +def system(session): + """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + system_test_path = os.path.join("tests", "system.py") + system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") + # Install pyopenssl for mTLS testing. + if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": + session.install("pyopenssl") + + system_test_exists = os.path.exists(system_test_path) + system_test_folder_exists = os.path.exists(system_test_folder_path) + # Sanity check: only run tests if found. + if not system_test_exists and not system_test_folder_exists: + session.skip("System tests were not found") + + install_systemtest_dependencies(session, "-c", constraints_path) + + # Run py.test against the system tests. + if system_test_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_path, + *session.posargs, + ) + if system_test_folder_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_folder_path, + *session.posargs, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "sphinx==4.5.0", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "gcp-sphinx-docfx-yaml", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python="3.12") +def prerelease_deps(session): + """Run all tests with prerelease versions of dependencies installed.""" + + # Install all dependencies + session.install("-e", ".[all, tests, tracing]") + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY + / "testing" + / f"constraints-{UNIT_TEST_PYTHON_VERSIONS[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "protobuf", + # dependency of grpc + "six", + "googleapis-common-protos", + # Exclude version 1.52.0rc1 which has a known issue. See https://github.com/grpc/grpc/issues/32163 + "grpcio!=1.52.0rc1", + "grpcio-status", + "google-api-core", + "google-auth", + "proto-plus", + "google-cloud-testutils", + # dependencies of google-cloud-testutils" + "click", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + + session.run("py.test", "tests/unit") diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_complete_import_space_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_complete_import_space_async.py new file mode 100644 index 000000000000..9675135ac7bc --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_complete_import_space_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CompleteImportSpace +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_CompleteImportSpace_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.apps import chat_v1 + + +async def sample_complete_import_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CompleteImportSpaceRequest( + name="name_value", + ) + + # Make the request + response = await client.complete_import_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CompleteImportSpace_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_complete_import_space_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_complete_import_space_sync.py new file mode 100644 index 000000000000..2b6fa285b602 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_complete_import_space_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CompleteImportSpace +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_CompleteImportSpace_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.apps import chat_v1 + + +def sample_complete_import_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CompleteImportSpaceRequest( + name="name_value", + ) + + # Make the request + response = client.complete_import_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CompleteImportSpace_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_membership_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_membership_async.py new file mode 100644 index 000000000000..b8ee8781cfed --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_membership_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateMembership +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_CreateMembership_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.apps import chat_v1 + + +async def sample_create_membership(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CreateMembershipRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_membership(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CreateMembership_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_membership_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_membership_sync.py new file mode 100644 index 000000000000..a590821917a6 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_membership_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateMembership +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_CreateMembership_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.apps import chat_v1 + + +def sample_create_membership(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CreateMembershipRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_membership(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CreateMembership_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_message_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_message_async.py new file mode 100644 index 000000000000..c01a9f2c5017 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_message_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateMessage +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_CreateMessage_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.apps import chat_v1 + + +async def sample_create_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CreateMessageRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_message(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CreateMessage_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_message_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_message_sync.py new file mode 100644 index 000000000000..2d319ad3090e --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_message_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateMessage +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_CreateMessage_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.apps import chat_v1 + + +def sample_create_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CreateMessageRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_message(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CreateMessage_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_reaction_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_reaction_async.py new file mode 100644 index 000000000000..538cbb7fb4ca --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_reaction_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateReaction +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_CreateReaction_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.apps import chat_v1 + + +async def sample_create_reaction(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CreateReactionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_reaction(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CreateReaction_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_reaction_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_reaction_sync.py new file mode 100644 index 000000000000..cfa633b6c46e --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_reaction_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateReaction +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_CreateReaction_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.apps import chat_v1 + + +def sample_create_reaction(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CreateReactionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_reaction(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CreateReaction_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_space_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_space_async.py new file mode 100644 index 000000000000..baa461d38ef8 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_space_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateSpace +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_CreateSpace_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.apps import chat_v1 + + +async def sample_create_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.CreateSpaceRequest( + ) + + # Make the request + response = await client.create_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CreateSpace_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_space_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_space_sync.py new file mode 100644 index 000000000000..2c2c25fc721d --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_create_space_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateSpace +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_CreateSpace_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.apps import chat_v1 + + +def sample_create_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.CreateSpaceRequest( + ) + + # Make the request + response = client.create_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_CreateSpace_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_membership_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_membership_async.py new file mode 100644 index 000000000000..1e6a388088e9 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_membership_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteMembership +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteMembership_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.apps import chat_v1 + + +async def sample_delete_membership(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMembershipRequest( + name="name_value", + ) + + # Make the request + response = await client.delete_membership(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_DeleteMembership_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_membership_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_membership_sync.py new file mode 100644 index 000000000000..bc8462afa3fb --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_membership_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteMembership +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteMembership_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.apps import chat_v1 + + +def sample_delete_membership(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMembershipRequest( + name="name_value", + ) + + # Make the request + response = client.delete_membership(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_DeleteMembership_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_message_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_message_async.py new file mode 100644 index 000000000000..3a38ebf1c107 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_message_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteMessage +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteMessage_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.apps import chat_v1 + + +async def sample_delete_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMessageRequest( + name="name_value", + ) + + # Make the request + await client.delete_message(request=request) + + +# [END chat_v1_generated_ChatService_DeleteMessage_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_message_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_message_sync.py new file mode 100644 index 000000000000..777341539222 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_message_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteMessage +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteMessage_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.apps import chat_v1 + + +def sample_delete_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteMessageRequest( + name="name_value", + ) + + # Make the request + client.delete_message(request=request) + + +# [END chat_v1_generated_ChatService_DeleteMessage_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_reaction_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_reaction_async.py new file mode 100644 index 000000000000..29eb1c1fb7e2 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_reaction_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteReaction +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteReaction_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.apps import chat_v1 + + +async def sample_delete_reaction(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteReactionRequest( + name="name_value", + ) + + # Make the request + await client.delete_reaction(request=request) + + +# [END chat_v1_generated_ChatService_DeleteReaction_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_reaction_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_reaction_sync.py new file mode 100644 index 000000000000..608308ed779d --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_reaction_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteReaction +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteReaction_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.apps import chat_v1 + + +def sample_delete_reaction(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteReactionRequest( + name="name_value", + ) + + # Make the request + client.delete_reaction(request=request) + + +# [END chat_v1_generated_ChatService_DeleteReaction_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_space_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_space_async.py new file mode 100644 index 000000000000..6b72a364ff88 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_space_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteSpace +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteSpace_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.apps import chat_v1 + + +async def sample_delete_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.DeleteSpaceRequest( + name="name_value", + ) + + # Make the request + await client.delete_space(request=request) + + +# [END chat_v1_generated_ChatService_DeleteSpace_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_space_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_space_sync.py new file mode 100644 index 000000000000..07c78de4763f --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_delete_space_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteSpace +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_DeleteSpace_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.apps import chat_v1 + + +def sample_delete_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.DeleteSpaceRequest( + name="name_value", + ) + + # Make the request + client.delete_space(request=request) + + +# [END chat_v1_generated_ChatService_DeleteSpace_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_find_direct_message_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_find_direct_message_async.py new file mode 100644 index 000000000000..8f6767cc7db2 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_find_direct_message_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 FindDirectMessage +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_FindDirectMessage_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.apps import chat_v1 + + +async def sample_find_direct_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.FindDirectMessageRequest( + name="name_value", + ) + + # Make the request + response = await client.find_direct_message(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_FindDirectMessage_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_find_direct_message_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_find_direct_message_sync.py new file mode 100644 index 000000000000..edde21bd19c7 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_find_direct_message_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 FindDirectMessage +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_FindDirectMessage_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.apps import chat_v1 + + +def sample_find_direct_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.FindDirectMessageRequest( + name="name_value", + ) + + # Make the request + response = client.find_direct_message(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_FindDirectMessage_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_attachment_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_attachment_async.py new file mode 100644 index 000000000000..8e46b4d6bf99 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_attachment_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetAttachment +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_GetAttachment_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.apps import chat_v1 + + +async def sample_get_attachment(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetAttachmentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_attachment(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetAttachment_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_attachment_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_attachment_sync.py new file mode 100644 index 000000000000..05b2531fff0a --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_attachment_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetAttachment +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_GetAttachment_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.apps import chat_v1 + + +def sample_get_attachment(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetAttachmentRequest( + name="name_value", + ) + + # Make the request + response = client.get_attachment(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetAttachment_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_membership_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_membership_async.py new file mode 100644 index 000000000000..cfeecdbe3871 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_membership_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetMembership +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_GetMembership_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.apps import chat_v1 + + +async def sample_get_membership(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetMembershipRequest( + name="name_value", + ) + + # Make the request + response = await client.get_membership(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetMembership_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_membership_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_membership_sync.py new file mode 100644 index 000000000000..098b1c1234b3 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_membership_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetMembership +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_GetMembership_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.apps import chat_v1 + + +def sample_get_membership(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetMembershipRequest( + name="name_value", + ) + + # Make the request + response = client.get_membership(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetMembership_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_message_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_message_async.py new file mode 100644 index 000000000000..84fb9263ef27 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_message_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetMessage +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_GetMessage_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.apps import chat_v1 + + +async def sample_get_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetMessageRequest( + name="name_value", + ) + + # Make the request + response = await client.get_message(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetMessage_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_message_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_message_sync.py new file mode 100644 index 000000000000..39f8f07d687b --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_message_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetMessage +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_GetMessage_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.apps import chat_v1 + + +def sample_get_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetMessageRequest( + name="name_value", + ) + + # Make the request + response = client.get_message(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetMessage_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_space_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_space_async.py new file mode 100644 index 000000000000..88940d1c15c4 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_space_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetSpace +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_GetSpace_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.apps import chat_v1 + + +async def sample_get_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.GetSpaceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetSpace_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_space_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_space_sync.py new file mode 100644 index 000000000000..a88068949ef7 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_get_space_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetSpace +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_GetSpace_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.apps import chat_v1 + + +def sample_get_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.GetSpaceRequest( + name="name_value", + ) + + # Make the request + response = client.get_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_GetSpace_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_memberships_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_memberships_async.py new file mode 100644 index 000000000000..8bc99f33a60a --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_memberships_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListMemberships +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_ListMemberships_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.apps import chat_v1 + + +async def sample_list_memberships(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListMembershipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memberships(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END chat_v1_generated_ChatService_ListMemberships_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_memberships_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_memberships_sync.py new file mode 100644 index 000000000000..4d26299c9329 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_memberships_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListMemberships +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_ListMemberships_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.apps import chat_v1 + + +def sample_list_memberships(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListMembershipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_memberships(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END chat_v1_generated_ChatService_ListMemberships_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_messages_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_messages_async.py new file mode 100644 index 000000000000..925adcae597e --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_messages_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListMessages +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_ListMessages_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.apps import chat_v1 + + +async def sample_list_messages(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListMessagesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_messages(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END chat_v1_generated_ChatService_ListMessages_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_messages_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_messages_sync.py new file mode 100644 index 000000000000..d3158c8e13c0 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_messages_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListMessages +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_ListMessages_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.apps import chat_v1 + + +def sample_list_messages(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListMessagesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_messages(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END chat_v1_generated_ChatService_ListMessages_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_reactions_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_reactions_async.py new file mode 100644 index 000000000000..1e373e1ad5ce --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_reactions_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListReactions +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_ListReactions_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.apps import chat_v1 + + +async def sample_list_reactions(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListReactionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_reactions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END chat_v1_generated_ChatService_ListReactions_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_reactions_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_reactions_sync.py new file mode 100644 index 000000000000..2e41b0f2b29e --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_reactions_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListReactions +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_ListReactions_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.apps import chat_v1 + + +def sample_list_reactions(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListReactionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_reactions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END chat_v1_generated_ChatService_ListReactions_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_spaces_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_spaces_async.py new file mode 100644 index 000000000000..920029f0c7bb --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_spaces_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListSpaces +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_ListSpaces_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.apps import chat_v1 + + +async def sample_list_spaces(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.ListSpacesRequest( + ) + + # Make the request + page_result = client.list_spaces(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END chat_v1_generated_ChatService_ListSpaces_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_spaces_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_spaces_sync.py new file mode 100644 index 000000000000..1d6047cc2957 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_list_spaces_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListSpaces +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_ListSpaces_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.apps import chat_v1 + + +def sample_list_spaces(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.ListSpacesRequest( + ) + + # Make the request + page_result = client.list_spaces(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END chat_v1_generated_ChatService_ListSpaces_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_set_up_space_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_set_up_space_async.py new file mode 100644 index 000000000000..96caf931e5c9 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_set_up_space_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 SetUpSpace +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_SetUpSpace_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.apps import chat_v1 + + +async def sample_set_up_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.SetUpSpaceRequest( + ) + + # Make the request + response = await client.set_up_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_SetUpSpace_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_set_up_space_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_set_up_space_sync.py new file mode 100644 index 000000000000..d271e4a3519b --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_set_up_space_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 SetUpSpace +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_SetUpSpace_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.apps import chat_v1 + + +def sample_set_up_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.SetUpSpaceRequest( + ) + + # Make the request + response = client.set_up_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_SetUpSpace_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_message_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_message_async.py new file mode 100644 index 000000000000..d796e2e17d15 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_message_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateMessage +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_UpdateMessage_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.apps import chat_v1 + + +async def sample_update_message(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UpdateMessageRequest( + ) + + # Make the request + response = await client.update_message(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_UpdateMessage_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_message_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_message_sync.py new file mode 100644 index 000000000000..a7aff061ffb0 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_message_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateMessage +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_UpdateMessage_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.apps import chat_v1 + + +def sample_update_message(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UpdateMessageRequest( + ) + + # Make the request + response = client.update_message(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_UpdateMessage_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_space_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_space_async.py new file mode 100644 index 000000000000..bcbeb4967b48 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_space_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateSpace +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_UpdateSpace_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.apps import chat_v1 + + +async def sample_update_space(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UpdateSpaceRequest( + ) + + # Make the request + response = await client.update_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_UpdateSpace_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_space_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_space_sync.py new file mode 100644 index 000000000000..f0af90f2adb8 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_update_space_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateSpace +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_UpdateSpace_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.apps import chat_v1 + + +def sample_update_space(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UpdateSpaceRequest( + ) + + # Make the request + response = client.update_space(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_UpdateSpace_sync] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_upload_attachment_async.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_upload_attachment_async.py new file mode 100644 index 000000000000..a114bb4d86a1 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_upload_attachment_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UploadAttachment +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_UploadAttachment_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.apps import chat_v1 + + +async def sample_upload_attachment(): + # Create a client + client = chat_v1.ChatServiceAsyncClient() + + # Initialize request argument(s) + request = chat_v1.UploadAttachmentRequest( + parent="parent_value", + filename="filename_value", + ) + + # Make the request + response = await client.upload_attachment(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_UploadAttachment_async] diff --git a/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_upload_attachment_sync.py b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_upload_attachment_sync.py new file mode 100644 index 000000000000..5a6b08e3d711 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/chat_v1_generated_chat_service_upload_attachment_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UploadAttachment +# 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-apps-chat + + +# [START chat_v1_generated_ChatService_UploadAttachment_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.apps import chat_v1 + + +def sample_upload_attachment(): + # Create a client + client = chat_v1.ChatServiceClient() + + # Initialize request argument(s) + request = chat_v1.UploadAttachmentRequest( + parent="parent_value", + filename="filename_value", + ) + + # Make the request + response = client.upload_attachment(request=request) + + # Handle the response + print(response) + +# [END chat_v1_generated_ChatService_UploadAttachment_sync] 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 new file mode 100644 index 000000000000..06e1e9c2ebf4 --- /dev/null +++ b/packages/google-apps-chat/samples/generated_samples/snippet_metadata_google.chat.v1.json @@ -0,0 +1,3547 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.chat.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-apps-chat", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.complete_import_space", + "method": { + "fullName": "google.chat.v1.ChatService.CompleteImportSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CompleteImportSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CompleteImportSpaceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.CompleteImportSpaceResponse", + "shortName": "complete_import_space" + }, + "description": "Sample for CompleteImportSpace", + "file": "chat_v1_generated_chat_service_complete_import_space_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CompleteImportSpace_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": "chat_v1_generated_chat_service_complete_import_space_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.complete_import_space", + "method": { + "fullName": "google.chat.v1.ChatService.CompleteImportSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CompleteImportSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CompleteImportSpaceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.CompleteImportSpaceResponse", + "shortName": "complete_import_space" + }, + "description": "Sample for CompleteImportSpace", + "file": "chat_v1_generated_chat_service_complete_import_space_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CompleteImportSpace_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": "chat_v1_generated_chat_service_complete_import_space_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.create_membership", + "method": { + "fullName": "google.chat.v1.ChatService.CreateMembership", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateMembershipRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "membership", + "type": "google.apps.chat_v1.types.Membership" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Membership", + "shortName": "create_membership" + }, + "description": "Sample for CreateMembership", + "file": "chat_v1_generated_chat_service_create_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateMembership_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": "chat_v1_generated_chat_service_create_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.create_membership", + "method": { + "fullName": "google.chat.v1.ChatService.CreateMembership", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateMembershipRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "membership", + "type": "google.apps.chat_v1.types.Membership" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Membership", + "shortName": "create_membership" + }, + "description": "Sample for CreateMembership", + "file": "chat_v1_generated_chat_service_create_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateMembership_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": "chat_v1_generated_chat_service_create_membership_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.create_message", + "method": { + "fullName": "google.chat.v1.ChatService.CreateMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateMessageRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "message", + "type": "google.apps.chat_v1.types.Message" + }, + { + "name": "message_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Message", + "shortName": "create_message" + }, + "description": "Sample for CreateMessage", + "file": "chat_v1_generated_chat_service_create_message_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateMessage_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": "chat_v1_generated_chat_service_create_message_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.create_message", + "method": { + "fullName": "google.chat.v1.ChatService.CreateMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateMessageRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "message", + "type": "google.apps.chat_v1.types.Message" + }, + { + "name": "message_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Message", + "shortName": "create_message" + }, + "description": "Sample for CreateMessage", + "file": "chat_v1_generated_chat_service_create_message_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateMessage_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": "chat_v1_generated_chat_service_create_message_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.create_reaction", + "method": { + "fullName": "google.chat.v1.ChatService.CreateReaction", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateReaction" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateReactionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "reaction", + "type": "google.apps.chat_v1.types.Reaction" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Reaction", + "shortName": "create_reaction" + }, + "description": "Sample for CreateReaction", + "file": "chat_v1_generated_chat_service_create_reaction_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateReaction_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": "chat_v1_generated_chat_service_create_reaction_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.create_reaction", + "method": { + "fullName": "google.chat.v1.ChatService.CreateReaction", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateReaction" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateReactionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "reaction", + "type": "google.apps.chat_v1.types.Reaction" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Reaction", + "shortName": "create_reaction" + }, + "description": "Sample for CreateReaction", + "file": "chat_v1_generated_chat_service_create_reaction_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateReaction_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": "chat_v1_generated_chat_service_create_reaction_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.create_space", + "method": { + "fullName": "google.chat.v1.ChatService.CreateSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateSpaceRequest" + }, + { + "name": "space", + "type": "google.apps.chat_v1.types.Space" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "create_space" + }, + "description": "Sample for CreateSpace", + "file": "chat_v1_generated_chat_service_create_space_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateSpace_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_create_space_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.create_space", + "method": { + "fullName": "google.chat.v1.ChatService.CreateSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "CreateSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.CreateSpaceRequest" + }, + { + "name": "space", + "type": "google.apps.chat_v1.types.Space" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "create_space" + }, + "description": "Sample for CreateSpace", + "file": "chat_v1_generated_chat_service_create_space_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_CreateSpace_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_create_space_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.delete_membership", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteMembership", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteMembershipRequest" + }, + { + "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.apps.chat_v1.types.Membership", + "shortName": "delete_membership" + }, + "description": "Sample for DeleteMembership", + "file": "chat_v1_generated_chat_service_delete_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteMembership_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": "chat_v1_generated_chat_service_delete_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.delete_membership", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteMembership", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteMembershipRequest" + }, + { + "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.apps.chat_v1.types.Membership", + "shortName": "delete_membership" + }, + "description": "Sample for DeleteMembership", + "file": "chat_v1_generated_chat_service_delete_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteMembership_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": "chat_v1_generated_chat_service_delete_membership_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.delete_message", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteMessageRequest" + }, + { + "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_message" + }, + "description": "Sample for DeleteMessage", + "file": "chat_v1_generated_chat_service_delete_message_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteMessage_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": "chat_v1_generated_chat_service_delete_message_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.delete_message", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteMessageRequest" + }, + { + "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_message" + }, + "description": "Sample for DeleteMessage", + "file": "chat_v1_generated_chat_service_delete_message_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteMessage_sync", + "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": "chat_v1_generated_chat_service_delete_message_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.delete_reaction", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteReaction", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteReaction" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteReactionRequest" + }, + { + "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_reaction" + }, + "description": "Sample for DeleteReaction", + "file": "chat_v1_generated_chat_service_delete_reaction_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteReaction_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": "chat_v1_generated_chat_service_delete_reaction_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.delete_reaction", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteReaction", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteReaction" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteReactionRequest" + }, + { + "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_reaction" + }, + "description": "Sample for DeleteReaction", + "file": "chat_v1_generated_chat_service_delete_reaction_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteReaction_sync", + "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": "chat_v1_generated_chat_service_delete_reaction_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.delete_space", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteSpaceRequest" + }, + { + "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_space" + }, + "description": "Sample for DeleteSpace", + "file": "chat_v1_generated_chat_service_delete_space_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteSpace_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": "chat_v1_generated_chat_service_delete_space_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.delete_space", + "method": { + "fullName": "google.chat.v1.ChatService.DeleteSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "DeleteSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.DeleteSpaceRequest" + }, + { + "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_space" + }, + "description": "Sample for DeleteSpace", + "file": "chat_v1_generated_chat_service_delete_space_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_DeleteSpace_sync", + "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": "chat_v1_generated_chat_service_delete_space_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.find_direct_message", + "method": { + "fullName": "google.chat.v1.ChatService.FindDirectMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "FindDirectMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.FindDirectMessageRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "find_direct_message" + }, + "description": "Sample for FindDirectMessage", + "file": "chat_v1_generated_chat_service_find_direct_message_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_FindDirectMessage_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": "chat_v1_generated_chat_service_find_direct_message_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.find_direct_message", + "method": { + "fullName": "google.chat.v1.ChatService.FindDirectMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "FindDirectMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.FindDirectMessageRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "find_direct_message" + }, + "description": "Sample for FindDirectMessage", + "file": "chat_v1_generated_chat_service_find_direct_message_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_FindDirectMessage_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": "chat_v1_generated_chat_service_find_direct_message_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.get_attachment", + "method": { + "fullName": "google.chat.v1.ChatService.GetAttachment", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetAttachment" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetAttachmentRequest" + }, + { + "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.apps.chat_v1.types.Attachment", + "shortName": "get_attachment" + }, + "description": "Sample for GetAttachment", + "file": "chat_v1_generated_chat_service_get_attachment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetAttachment_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": "chat_v1_generated_chat_service_get_attachment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.get_attachment", + "method": { + "fullName": "google.chat.v1.ChatService.GetAttachment", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetAttachment" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetAttachmentRequest" + }, + { + "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.apps.chat_v1.types.Attachment", + "shortName": "get_attachment" + }, + "description": "Sample for GetAttachment", + "file": "chat_v1_generated_chat_service_get_attachment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetAttachment_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": "chat_v1_generated_chat_service_get_attachment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.get_membership", + "method": { + "fullName": "google.chat.v1.ChatService.GetMembership", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetMembershipRequest" + }, + { + "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.apps.chat_v1.types.Membership", + "shortName": "get_membership" + }, + "description": "Sample for GetMembership", + "file": "chat_v1_generated_chat_service_get_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetMembership_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": "chat_v1_generated_chat_service_get_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.get_membership", + "method": { + "fullName": "google.chat.v1.ChatService.GetMembership", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetMembershipRequest" + }, + { + "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.apps.chat_v1.types.Membership", + "shortName": "get_membership" + }, + "description": "Sample for GetMembership", + "file": "chat_v1_generated_chat_service_get_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetMembership_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": "chat_v1_generated_chat_service_get_membership_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.get_message", + "method": { + "fullName": "google.chat.v1.ChatService.GetMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetMessageRequest" + }, + { + "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.apps.chat_v1.types.Message", + "shortName": "get_message" + }, + "description": "Sample for GetMessage", + "file": "chat_v1_generated_chat_service_get_message_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetMessage_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": "chat_v1_generated_chat_service_get_message_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.get_message", + "method": { + "fullName": "google.chat.v1.ChatService.GetMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetMessageRequest" + }, + { + "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.apps.chat_v1.types.Message", + "shortName": "get_message" + }, + "description": "Sample for GetMessage", + "file": "chat_v1_generated_chat_service_get_message_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetMessage_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": "chat_v1_generated_chat_service_get_message_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.get_space", + "method": { + "fullName": "google.chat.v1.ChatService.GetSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetSpaceRequest" + }, + { + "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.apps.chat_v1.types.Space", + "shortName": "get_space" + }, + "description": "Sample for GetSpace", + "file": "chat_v1_generated_chat_service_get_space_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetSpace_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": "chat_v1_generated_chat_service_get_space_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.get_space", + "method": { + "fullName": "google.chat.v1.ChatService.GetSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "GetSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.GetSpaceRequest" + }, + { + "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.apps.chat_v1.types.Space", + "shortName": "get_space" + }, + "description": "Sample for GetSpace", + "file": "chat_v1_generated_chat_service_get_space_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_GetSpace_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": "chat_v1_generated_chat_service_get_space_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.list_memberships", + "method": { + "fullName": "google.chat.v1.ChatService.ListMemberships", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListMemberships" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListMembershipsRequest" + }, + { + "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.apps.chat_v1.services.chat_service.pagers.ListMembershipsAsyncPager", + "shortName": "list_memberships" + }, + "description": "Sample for ListMemberships", + "file": "chat_v1_generated_chat_service_list_memberships_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListMemberships_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": "chat_v1_generated_chat_service_list_memberships_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.list_memberships", + "method": { + "fullName": "google.chat.v1.ChatService.ListMemberships", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListMemberships" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListMembershipsRequest" + }, + { + "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.apps.chat_v1.services.chat_service.pagers.ListMembershipsPager", + "shortName": "list_memberships" + }, + "description": "Sample for ListMemberships", + "file": "chat_v1_generated_chat_service_list_memberships_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListMemberships_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": "chat_v1_generated_chat_service_list_memberships_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.list_messages", + "method": { + "fullName": "google.chat.v1.ChatService.ListMessages", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListMessages" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListMessagesRequest" + }, + { + "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.apps.chat_v1.services.chat_service.pagers.ListMessagesAsyncPager", + "shortName": "list_messages" + }, + "description": "Sample for ListMessages", + "file": "chat_v1_generated_chat_service_list_messages_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListMessages_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": "chat_v1_generated_chat_service_list_messages_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.list_messages", + "method": { + "fullName": "google.chat.v1.ChatService.ListMessages", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListMessages" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListMessagesRequest" + }, + { + "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.apps.chat_v1.services.chat_service.pagers.ListMessagesPager", + "shortName": "list_messages" + }, + "description": "Sample for ListMessages", + "file": "chat_v1_generated_chat_service_list_messages_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListMessages_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": "chat_v1_generated_chat_service_list_messages_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.list_reactions", + "method": { + "fullName": "google.chat.v1.ChatService.ListReactions", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListReactions" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListReactionsRequest" + }, + { + "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.apps.chat_v1.services.chat_service.pagers.ListReactionsAsyncPager", + "shortName": "list_reactions" + }, + "description": "Sample for ListReactions", + "file": "chat_v1_generated_chat_service_list_reactions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListReactions_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": "chat_v1_generated_chat_service_list_reactions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.list_reactions", + "method": { + "fullName": "google.chat.v1.ChatService.ListReactions", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListReactions" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListReactionsRequest" + }, + { + "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.apps.chat_v1.services.chat_service.pagers.ListReactionsPager", + "shortName": "list_reactions" + }, + "description": "Sample for ListReactions", + "file": "chat_v1_generated_chat_service_list_reactions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListReactions_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": "chat_v1_generated_chat_service_list_reactions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.list_spaces", + "method": { + "fullName": "google.chat.v1.ChatService.ListSpaces", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListSpaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListSpacesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListSpacesAsyncPager", + "shortName": "list_spaces" + }, + "description": "Sample for ListSpaces", + "file": "chat_v1_generated_chat_service_list_spaces_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListSpaces_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_list_spaces_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.list_spaces", + "method": { + "fullName": "google.chat.v1.ChatService.ListSpaces", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "ListSpaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.ListSpacesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.services.chat_service.pagers.ListSpacesPager", + "shortName": "list_spaces" + }, + "description": "Sample for ListSpaces", + "file": "chat_v1_generated_chat_service_list_spaces_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_ListSpaces_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_list_spaces_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.set_up_space", + "method": { + "fullName": "google.chat.v1.ChatService.SetUpSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "SetUpSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.SetUpSpaceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "set_up_space" + }, + "description": "Sample for SetUpSpace", + "file": "chat_v1_generated_chat_service_set_up_space_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_SetUpSpace_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_set_up_space_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.set_up_space", + "method": { + "fullName": "google.chat.v1.ChatService.SetUpSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "SetUpSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.SetUpSpaceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.Space", + "shortName": "set_up_space" + }, + "description": "Sample for SetUpSpace", + "file": "chat_v1_generated_chat_service_set_up_space_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_SetUpSpace_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_set_up_space_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.update_message", + "method": { + "fullName": "google.chat.v1.ChatService.UpdateMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UpdateMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UpdateMessageRequest" + }, + { + "name": "message", + "type": "google.apps.chat_v1.types.Message" + }, + { + "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.apps.chat_v1.types.Message", + "shortName": "update_message" + }, + "description": "Sample for UpdateMessage", + "file": "chat_v1_generated_chat_service_update_message_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UpdateMessage_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_update_message_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.update_message", + "method": { + "fullName": "google.chat.v1.ChatService.UpdateMessage", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UpdateMessage" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UpdateMessageRequest" + }, + { + "name": "message", + "type": "google.apps.chat_v1.types.Message" + }, + { + "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.apps.chat_v1.types.Message", + "shortName": "update_message" + }, + "description": "Sample for UpdateMessage", + "file": "chat_v1_generated_chat_service_update_message_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UpdateMessage_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_update_message_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.update_space", + "method": { + "fullName": "google.chat.v1.ChatService.UpdateSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UpdateSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UpdateSpaceRequest" + }, + { + "name": "space", + "type": "google.apps.chat_v1.types.Space" + }, + { + "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.apps.chat_v1.types.Space", + "shortName": "update_space" + }, + "description": "Sample for UpdateSpace", + "file": "chat_v1_generated_chat_service_update_space_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UpdateSpace_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_update_space_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.update_space", + "method": { + "fullName": "google.chat.v1.ChatService.UpdateSpace", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UpdateSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UpdateSpaceRequest" + }, + { + "name": "space", + "type": "google.apps.chat_v1.types.Space" + }, + { + "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.apps.chat_v1.types.Space", + "shortName": "update_space" + }, + "description": "Sample for UpdateSpace", + "file": "chat_v1_generated_chat_service_update_space_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UpdateSpace_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chat_v1_generated_chat_service_update_space_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient", + "shortName": "ChatServiceAsyncClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceAsyncClient.upload_attachment", + "method": { + "fullName": "google.chat.v1.ChatService.UploadAttachment", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UploadAttachment" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UploadAttachmentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.UploadAttachmentResponse", + "shortName": "upload_attachment" + }, + "description": "Sample for UploadAttachment", + "file": "chat_v1_generated_chat_service_upload_attachment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UploadAttachment_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": "chat_v1_generated_chat_service_upload_attachment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.apps.chat_v1.ChatServiceClient", + "shortName": "ChatServiceClient" + }, + "fullName": "google.apps.chat_v1.ChatServiceClient.upload_attachment", + "method": { + "fullName": "google.chat.v1.ChatService.UploadAttachment", + "service": { + "fullName": "google.chat.v1.ChatService", + "shortName": "ChatService" + }, + "shortName": "UploadAttachment" + }, + "parameters": [ + { + "name": "request", + "type": "google.apps.chat_v1.types.UploadAttachmentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.apps.chat_v1.types.UploadAttachmentResponse", + "shortName": "upload_attachment" + }, + "description": "Sample for UploadAttachment", + "file": "chat_v1_generated_chat_service_upload_attachment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chat_v1_generated_ChatService_UploadAttachment_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": "chat_v1_generated_chat_service_upload_attachment_sync.py" + } + ] +} diff --git a/packages/google-apps-chat/scripts/decrypt-secrets.sh b/packages/google-apps-chat/scripts/decrypt-secrets.sh new file mode 100755 index 000000000000..0018b421ddf8 --- /dev/null +++ b/packages/google-apps-chat/scripts/decrypt-secrets.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# Copyright 2023 Google LLC All rights reserved. +# +# 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. + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +ROOT=$( dirname "$DIR" ) + +# Work from the project root. +cd $ROOT + +# Prevent it from overriding files. +# We recommend that sample authors use their own service account files and cloud project. +# In that case, they are supposed to prepare these files by themselves. +if [[ -f "testing/test-env.sh" ]] || \ + [[ -f "testing/service-account.json" ]] || \ + [[ -f "testing/client-secrets.json" ]]; then + echo "One or more target files exist, aborting." + exit 1 +fi + +# Use SECRET_MANAGER_PROJECT if set, fallback to cloud-devrel-kokoro-resources. +PROJECT_ID="${SECRET_MANAGER_PROJECT:-cloud-devrel-kokoro-resources}" + +gcloud secrets versions access latest --secret="python-docs-samples-test-env" \ + --project="${PROJECT_ID}" \ + > testing/test-env.sh +gcloud secrets versions access latest \ + --secret="python-docs-samples-service-account" \ + --project="${PROJECT_ID}" \ + > testing/service-account.json +gcloud secrets versions access latest \ + --secret="python-docs-samples-client-secrets" \ + --project="${PROJECT_ID}" \ + > testing/client-secrets.json diff --git a/packages/google-apps-chat/scripts/fixup_chat_v1_keywords.py b/packages/google-apps-chat/scripts/fixup_chat_v1_keywords.py new file mode 100644 index 000000000000..0a971a7a9d72 --- /dev/null +++ b/packages/google-apps-chat/scripts/fixup_chat_v1_keywords.py @@ -0,0 +1,197 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class chatCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'complete_import_space': ('name', ), + 'create_membership': ('parent', 'membership', ), + 'create_message': ('parent', 'message', 'thread_key', 'request_id', 'message_reply_option', 'message_id', ), + 'create_reaction': ('parent', 'reaction', ), + 'create_space': ('space', 'request_id', ), + 'delete_membership': ('name', ), + 'delete_message': ('name', 'force', ), + 'delete_reaction': ('name', ), + 'delete_space': ('name', ), + 'find_direct_message': ('name', ), + 'get_attachment': ('name', ), + 'get_membership': ('name', ), + 'get_message': ('name', ), + 'get_space': ('name', ), + 'list_memberships': ('parent', 'page_size', 'page_token', 'filter', 'show_groups', 'show_invited', ), + 'list_messages': ('parent', 'page_size', 'page_token', 'filter', 'order_by', 'show_deleted', ), + 'list_reactions': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_spaces': ('page_size', 'page_token', 'filter', ), + 'set_up_space': ('space', 'request_id', 'memberships', ), + 'update_message': ('message', 'update_mask', 'allow_missing', ), + 'update_space': ('space', 'update_mask', ), + 'upload_attachment': ('parent', 'filename', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=chatCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the chat client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/packages/google-apps-chat/setup.py b/packages/google-apps-chat/setup.py new file mode 100644 index 000000000000..f8e9fa71c8c6 --- /dev/null +++ b/packages/google-apps-chat/setup.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = "google-apps-chat" + + +description = "Google Apps Chat API client library" + +version = None + +with open(os.path.join(package_root, "google/apps/chat/gapic_version.py")) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert len(version_candidates) == 1 + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "google-apps-card >= 0.1.0, <1.0.0dev", + "google-auth >= 2.14.1, <3.0.0dev", + "proto-plus >= 1.22.3, <2.0.0dev", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-chat" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/packages/google-apps-chat/testing/.gitignore b/packages/google-apps-chat/testing/.gitignore new file mode 100644 index 000000000000..b05fbd630881 --- /dev/null +++ b/packages/google-apps-chat/testing/.gitignore @@ -0,0 +1,3 @@ +test-env.sh +service-account.json +client-secrets.json \ No newline at end of file diff --git a/packages/google-apps-chat/testing/constraints-3.10.txt b/packages/google-apps-chat/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-apps-chat/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-apps-chat/testing/constraints-3.11.txt b/packages/google-apps-chat/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-apps-chat/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-apps-chat/testing/constraints-3.12.txt b/packages/google-apps-chat/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-apps-chat/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-apps-chat/testing/constraints-3.7.txt b/packages/google-apps-chat/testing/constraints-3.7.txt new file mode 100644 index 000000000000..5098e5ae4a56 --- /dev/null +++ b/packages/google-apps-chat/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-apps-card==0.1.0 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.19.5 diff --git a/packages/google-apps-chat/testing/constraints-3.8.txt b/packages/google-apps-chat/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-apps-chat/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-apps-chat/testing/constraints-3.9.txt b/packages/google-apps-chat/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-apps-chat/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-apps-chat/tests/__init__.py b/packages/google-apps-chat/tests/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-apps-chat/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-apps-chat/tests/unit/__init__.py b/packages/google-apps-chat/tests/unit/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-apps-chat/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-apps-chat/tests/unit/gapic/__init__.py b/packages/google-apps-chat/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-apps-chat/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-apps-chat/tests/unit/gapic/chat_v1/__init__.py b/packages/google-apps-chat/tests/unit/gapic/chat_v1/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-apps-chat/tests/unit/gapic/chat_v1/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# 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 new file mode 100644 index 000000000000..ed2ce5f50853 --- /dev/null +++ b/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py @@ -0,0 +1,14803 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import Iterable +import json +import math + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +from google.apps.card_v1.types import card +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.rpc import code_pb2 # type: ignore +from google.type import color_pb2 # type: ignore +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +from google.apps.chat_v1.services.chat_service import ( + ChatServiceAsyncClient, + ChatServiceClient, + pagers, + transports, +) +from google.apps.chat_v1.types import ( + action_status, + annotation, + attachment, + contextual_addon, + deletion_metadata, + group, + history_state, + matched_url, +) +from google.apps.chat_v1.types import membership +from google.apps.chat_v1.types import membership as gc_membership +from google.apps.chat_v1.types import message +from google.apps.chat_v1.types import message as gc_message +from google.apps.chat_v1.types import reaction +from google.apps.chat_v1.types import reaction as gc_reaction +from google.apps.chat_v1.types import slash_command +from google.apps.chat_v1.types import space +from google.apps.chat_v1.types import space as gc_space +from google.apps.chat_v1.types import space_setup, user, widgets + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ChatServiceClient._get_default_mtls_endpoint(None) is None + assert ( + ChatServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + ChatServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ChatServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ChatServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ChatServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +def test__read_environment_variables(): + assert ChatServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ChatServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ChatServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + ChatServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ChatServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ChatServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ChatServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ChatServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert ChatServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert ChatServiceClient._get_client_cert_source(None, False) is None + assert ( + ChatServiceClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + ChatServiceClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + ChatServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + ChatServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + ChatServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ChatServiceClient), +) +@mock.patch.object( + ChatServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ChatServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ChatServiceClient._DEFAULT_UNIVERSE + default_endpoint = ChatServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ChatServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + ChatServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + ChatServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == ChatServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ChatServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + ChatServiceClient._get_api_endpoint(None, None, default_universe, "always") + == ChatServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ChatServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == ChatServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ChatServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + ChatServiceClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + ChatServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + ChatServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + ChatServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + ChatServiceClient._get_universe_domain(None, None) + == ChatServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + ChatServiceClient._get_universe_domain("", None) + 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", + [ + (ChatServiceClient, "grpc"), + (ChatServiceAsyncClient, "grpc_asyncio"), + (ChatServiceClient, "rest"), + ], +) +def test_chat_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "chat.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://chat.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.ChatServiceGrpcTransport, "grpc"), + (transports.ChatServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ChatServiceRestTransport, "rest"), + ], +) +def test_chat_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ChatServiceClient, "grpc"), + (ChatServiceAsyncClient, "grpc_asyncio"), + (ChatServiceClient, "rest"), + ], +) +def test_chat_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "chat.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://chat.googleapis.com" + ) + + +def test_chat_service_client_get_transport_class(): + transport = ChatServiceClient.get_transport_class() + available_transports = [ + transports.ChatServiceGrpcTransport, + transports.ChatServiceRestTransport, + ] + assert transport in available_transports + + transport = ChatServiceClient.get_transport_class("grpc") + assert transport == transports.ChatServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ChatServiceClient, transports.ChatServiceGrpcTransport, "grpc"), + ( + ChatServiceAsyncClient, + transports.ChatServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (ChatServiceClient, transports.ChatServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + ChatServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ChatServiceClient), +) +@mock.patch.object( + ChatServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ChatServiceAsyncClient), +) +def test_chat_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ChatServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(ChatServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ChatServiceClient, transports.ChatServiceGrpcTransport, "grpc", "true"), + ( + ChatServiceAsyncClient, + transports.ChatServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ChatServiceClient, transports.ChatServiceGrpcTransport, "grpc", "false"), + ( + ChatServiceAsyncClient, + transports.ChatServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (ChatServiceClient, transports.ChatServiceRestTransport, "rest", "true"), + (ChatServiceClient, transports.ChatServiceRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + ChatServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ChatServiceClient), +) +@mock.patch.object( + ChatServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ChatServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_chat_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ChatServiceClient, ChatServiceAsyncClient]) +@mock.patch.object( + ChatServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ChatServiceClient) +) +@mock.patch.object( + ChatServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ChatServiceAsyncClient), +) +def test_chat_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize("client_class", [ChatServiceClient, ChatServiceAsyncClient]) +@mock.patch.object( + ChatServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ChatServiceClient), +) +@mock.patch.object( + ChatServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ChatServiceAsyncClient), +) +def test_chat_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ChatServiceClient._DEFAULT_UNIVERSE + default_endpoint = ChatServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ChatServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ChatServiceClient, transports.ChatServiceGrpcTransport, "grpc"), + ( + ChatServiceAsyncClient, + transports.ChatServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (ChatServiceClient, transports.ChatServiceRestTransport, "rest"), + ], +) +def test_chat_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (ChatServiceClient, transports.ChatServiceGrpcTransport, "grpc", grpc_helpers), + ( + ChatServiceAsyncClient, + transports.ChatServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (ChatServiceClient, transports.ChatServiceRestTransport, "rest", None), + ], +) +def test_chat_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_chat_service_client_client_options_from_dict(): + with mock.patch( + "google.apps.chat_v1.services.chat_service.transports.ChatServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ChatServiceClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (ChatServiceClient, transports.ChatServiceGrpcTransport, "grpc", grpc_helpers), + ( + ChatServiceAsyncClient, + transports.ChatServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_chat_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "chat.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/chat.bot", + "https://www.googleapis.com/auth/chat.delete", + "https://www.googleapis.com/auth/chat.import", + "https://www.googleapis.com/auth/chat.memberships", + "https://www.googleapis.com/auth/chat.memberships.app", + "https://www.googleapis.com/auth/chat.memberships.readonly", + "https://www.googleapis.com/auth/chat.messages", + "https://www.googleapis.com/auth/chat.messages.create", + "https://www.googleapis.com/auth/chat.messages.reactions", + "https://www.googleapis.com/auth/chat.messages.reactions.create", + "https://www.googleapis.com/auth/chat.messages.reactions.readonly", + "https://www.googleapis.com/auth/chat.messages.readonly", + "https://www.googleapis.com/auth/chat.spaces", + "https://www.googleapis.com/auth/chat.spaces.create", + "https://www.googleapis.com/auth/chat.spaces.readonly", + ), + scopes=None, + default_host="chat.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_message.CreateMessageRequest, + dict, + ], +) +def test_create_message(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_message.Message( + name="name_value", + text="text_value", + formatted_text="formatted_text_value", + fallback_text="fallback_text_value", + argument_text="argument_text_value", + thread_reply=True, + client_assigned_message_id="client_assigned_message_id_value", + ) + response = client.create_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gc_message.CreateMessageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_message.Message) + assert response.name == "name_value" + assert response.text == "text_value" + assert response.formatted_text == "formatted_text_value" + assert response.fallback_text == "fallback_text_value" + assert response.argument_text == "argument_text_value" + assert response.thread_reply is True + assert response.client_assigned_message_id == "client_assigned_message_id_value" + + +def test_create_message_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_message), "__call__") as call: + client.create_message() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_message.CreateMessageRequest() + + +@pytest.mark.asyncio +async def test_create_message_async( + transport: str = "grpc_asyncio", request_type=gc_message.CreateMessageRequest +): + client = ChatServiceAsyncClient( + 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_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_message.Message( + name="name_value", + text="text_value", + formatted_text="formatted_text_value", + fallback_text="fallback_text_value", + argument_text="argument_text_value", + thread_reply=True, + client_assigned_message_id="client_assigned_message_id_value", + ) + ) + response = await client.create_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gc_message.CreateMessageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_message.Message) + assert response.name == "name_value" + assert response.text == "text_value" + assert response.formatted_text == "formatted_text_value" + assert response.fallback_text == "fallback_text_value" + assert response.argument_text == "argument_text_value" + assert response.thread_reply is True + assert response.client_assigned_message_id == "client_assigned_message_id_value" + + +@pytest.mark.asyncio +async def test_create_message_async_from_dict(): + await test_create_message_async(request_type=dict) + + +def test_create_message_field_headers(): + client = ChatServiceClient( + 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 = gc_message.CreateMessageRequest() + + 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), "__call__") as call: + call.return_value = gc_message.Message() + client.create_message(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_message_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = gc_message.CreateMessageRequest() + + 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), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_message.Message()) + await client.create_message(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_message_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_message.Message() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_message( + parent="parent_value", + message=gc_message.Message(name="name_value"), + message_id="message_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].message + mock_val = gc_message.Message(name="name_value") + assert arg == mock_val + arg = args[0].message_id + mock_val = "message_id_value" + assert arg == mock_val + + +def test_create_message_flattened_error(): + client = ChatServiceClient( + 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_message( + gc_message.CreateMessageRequest(), + parent="parent_value", + message=gc_message.Message(name="name_value"), + message_id="message_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_message_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_message.Message() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_message.Message()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_message( + parent="parent_value", + message=gc_message.Message(name="name_value"), + message_id="message_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].message + mock_val = gc_message.Message(name="name_value") + assert arg == mock_val + arg = args[0].message_id + mock_val = "message_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_message_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_message( + gc_message.CreateMessageRequest(), + parent="parent_value", + message=gc_message.Message(name="name_value"), + message_id="message_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + message.ListMessagesRequest, + dict, + ], +) +def test_list_messages(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_messages), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = message.ListMessagesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_messages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == message.ListMessagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessagesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_messages_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_messages), "__call__") as call: + client.list_messages() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == message.ListMessagesRequest() + + +@pytest.mark.asyncio +async def test_list_messages_async( + transport: str = "grpc_asyncio", request_type=message.ListMessagesRequest +): + client = ChatServiceAsyncClient( + 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_messages), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + message.ListMessagesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_messages(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == message.ListMessagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessagesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_messages_async_from_dict(): + await test_list_messages_async(request_type=dict) + + +def test_list_messages_field_headers(): + client = ChatServiceClient( + 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 = message.ListMessagesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_messages), "__call__") as call: + call.return_value = message.ListMessagesResponse() + client.list_messages(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_messages_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = message.ListMessagesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_messages), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + message.ListMessagesResponse() + ) + await client.list_messages(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_messages_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_messages), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = message.ListMessagesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_messages( + 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_messages_flattened_error(): + client = ChatServiceClient( + 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_messages( + message.ListMessagesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_messages_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_messages), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = message.ListMessagesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + message.ListMessagesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_messages( + 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_messages_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_messages( + message.ListMessagesRequest(), + parent="parent_value", + ) + + +def test_list_messages_pager(transport_name: str = "grpc"): + client = ChatServiceClient( + 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_messages), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + message.Message(), + ], + next_page_token="abc", + ), + message.ListMessagesResponse( + messages=[], + next_page_token="def", + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + ], + next_page_token="ghi", + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_messages(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, message.Message) for i in results) + + +def test_list_messages_pages(transport_name: str = "grpc"): + client = ChatServiceClient( + 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_messages), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + message.Message(), + ], + next_page_token="abc", + ), + message.ListMessagesResponse( + messages=[], + next_page_token="def", + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + ], + next_page_token="ghi", + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + ], + ), + RuntimeError, + ) + pages = list(client.list_messages(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_messages_async_pager(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + message.Message(), + ], + next_page_token="abc", + ), + message.ListMessagesResponse( + messages=[], + next_page_token="def", + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + ], + next_page_token="ghi", + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_messages( + 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, message.Message) for i in responses) + + +@pytest.mark.asyncio +async def test_list_messages_async_pages(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_messages), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + message.Message(), + ], + next_page_token="abc", + ), + message.ListMessagesResponse( + messages=[], + next_page_token="def", + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + ], + next_page_token="ghi", + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + ], + ), + 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_messages(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", + [ + membership.ListMembershipsRequest, + dict, + ], +) +def test_list_memberships(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_memberships), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = membership.ListMembershipsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_memberships(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == membership.ListMembershipsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_memberships_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_memberships), "__call__") as call: + client.list_memberships() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.ListMembershipsRequest() + + +@pytest.mark.asyncio +async def test_list_memberships_async( + transport: str = "grpc_asyncio", request_type=membership.ListMembershipsRequest +): + client = ChatServiceAsyncClient( + 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_memberships), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + membership.ListMembershipsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_memberships(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == membership.ListMembershipsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_memberships_async_from_dict(): + await test_list_memberships_async(request_type=dict) + + +def test_list_memberships_field_headers(): + client = ChatServiceClient( + 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 = membership.ListMembershipsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_memberships), "__call__") as call: + call.return_value = membership.ListMembershipsResponse() + client.list_memberships(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_memberships_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = membership.ListMembershipsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_memberships), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + membership.ListMembershipsResponse() + ) + await client.list_memberships(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_memberships_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_memberships), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = membership.ListMembershipsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_memberships( + 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_memberships_flattened_error(): + client = ChatServiceClient( + 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_memberships( + membership.ListMembershipsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_memberships_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_memberships), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = membership.ListMembershipsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + membership.ListMembershipsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_memberships( + 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_memberships_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_memberships( + membership.ListMembershipsRequest(), + parent="parent_value", + ) + + +def test_list_memberships_pager(transport_name: str = "grpc"): + client = ChatServiceClient( + 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_memberships), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token="abc", + ), + membership.ListMembershipsResponse( + memberships=[], + next_page_token="def", + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + ], + next_page_token="ghi", + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_memberships(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, membership.Membership) for i in results) + + +def test_list_memberships_pages(transport_name: str = "grpc"): + client = ChatServiceClient( + 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_memberships), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token="abc", + ), + membership.ListMembershipsResponse( + memberships=[], + next_page_token="def", + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + ], + next_page_token="ghi", + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + ], + ), + RuntimeError, + ) + pages = list(client.list_memberships(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_memberships_async_pager(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token="abc", + ), + membership.ListMembershipsResponse( + memberships=[], + next_page_token="def", + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + ], + next_page_token="ghi", + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_memberships( + 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, membership.Membership) for i in responses) + + +@pytest.mark.asyncio +async def test_list_memberships_async_pages(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_memberships), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token="abc", + ), + membership.ListMembershipsResponse( + memberships=[], + next_page_token="def", + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + ], + next_page_token="ghi", + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + ], + ), + 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_memberships(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", + [ + membership.GetMembershipRequest, + dict, + ], +) +def test_get_membership(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_membership), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership( + name="name_value", + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + ) + response = client.get_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == membership.GetMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == "name_value" + assert response.state == membership.Membership.MembershipState.JOINED + assert response.role == membership.Membership.MembershipRole.ROLE_MEMBER + + +def test_get_membership_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + client.get_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.GetMembershipRequest() + + +@pytest.mark.asyncio +async def test_get_membership_async( + transport: str = "grpc_asyncio", request_type=membership.GetMembershipRequest +): + client = ChatServiceAsyncClient( + 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_membership), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + membership.Membership( + name="name_value", + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + ) + ) + response = await client.get_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == membership.GetMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == "name_value" + assert response.state == membership.Membership.MembershipState.JOINED + assert response.role == membership.Membership.MembershipRole.ROLE_MEMBER + + +@pytest.mark.asyncio +async def test_get_membership_async_from_dict(): + await test_get_membership_async(request_type=dict) + + +def test_get_membership_field_headers(): + client = ChatServiceClient( + 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 = membership.GetMembershipRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + call.return_value = membership.Membership() + client.get_membership(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_membership_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = membership.GetMembershipRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + membership.Membership() + ) + await client.get_membership(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_membership_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_membership( + 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_membership_flattened_error(): + client = ChatServiceClient( + 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_membership( + membership.GetMembershipRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_membership_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + membership.Membership() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_membership( + 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_membership_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_membership( + membership.GetMembershipRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + message.GetMessageRequest, + dict, + ], +) +def test_get_message(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = message.Message( + name="name_value", + text="text_value", + formatted_text="formatted_text_value", + fallback_text="fallback_text_value", + argument_text="argument_text_value", + thread_reply=True, + client_assigned_message_id="client_assigned_message_id_value", + ) + response = client.get_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == message.GetMessageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, message.Message) + assert response.name == "name_value" + assert response.text == "text_value" + assert response.formatted_text == "formatted_text_value" + assert response.fallback_text == "fallback_text_value" + assert response.argument_text == "argument_text_value" + assert response.thread_reply is True + assert response.client_assigned_message_id == "client_assigned_message_id_value" + + +def test_get_message_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_message), "__call__") as call: + client.get_message() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == message.GetMessageRequest() + + +@pytest.mark.asyncio +async def test_get_message_async( + transport: str = "grpc_asyncio", request_type=message.GetMessageRequest +): + client = ChatServiceAsyncClient( + 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), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + message.Message( + name="name_value", + text="text_value", + formatted_text="formatted_text_value", + fallback_text="fallback_text_value", + argument_text="argument_text_value", + thread_reply=True, + client_assigned_message_id="client_assigned_message_id_value", + ) + ) + response = await client.get_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == message.GetMessageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, message.Message) + assert response.name == "name_value" + assert response.text == "text_value" + assert response.formatted_text == "formatted_text_value" + assert response.fallback_text == "fallback_text_value" + assert response.argument_text == "argument_text_value" + assert response.thread_reply is True + assert response.client_assigned_message_id == "client_assigned_message_id_value" + + +@pytest.mark.asyncio +async def test_get_message_async_from_dict(): + await test_get_message_async(request_type=dict) + + +def test_get_message_field_headers(): + client = ChatServiceClient( + 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 = message.GetMessageRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_message), "__call__") as call: + call.return_value = message.Message() + client.get_message(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_message_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = message.GetMessageRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_message), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(message.Message()) + await client.get_message(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_message_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = message.Message() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_message( + 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_message_flattened_error(): + client = ChatServiceClient( + 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_message( + message.GetMessageRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_message_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_message), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = message.Message() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(message.Message()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_message( + 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_message_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_message( + message.GetMessageRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_message.UpdateMessageRequest, + dict, + ], +) +def test_update_message(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_message.Message( + name="name_value", + text="text_value", + formatted_text="formatted_text_value", + fallback_text="fallback_text_value", + argument_text="argument_text_value", + thread_reply=True, + client_assigned_message_id="client_assigned_message_id_value", + ) + response = client.update_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gc_message.UpdateMessageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_message.Message) + assert response.name == "name_value" + assert response.text == "text_value" + assert response.formatted_text == "formatted_text_value" + assert response.fallback_text == "fallback_text_value" + assert response.argument_text == "argument_text_value" + assert response.thread_reply is True + assert response.client_assigned_message_id == "client_assigned_message_id_value" + + +def test_update_message_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_message), "__call__") as call: + client.update_message() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_message.UpdateMessageRequest() + + +@pytest.mark.asyncio +async def test_update_message_async( + transport: str = "grpc_asyncio", request_type=gc_message.UpdateMessageRequest +): + client = ChatServiceAsyncClient( + 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), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_message.Message( + name="name_value", + text="text_value", + formatted_text="formatted_text_value", + fallback_text="fallback_text_value", + argument_text="argument_text_value", + thread_reply=True, + client_assigned_message_id="client_assigned_message_id_value", + ) + ) + response = await client.update_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gc_message.UpdateMessageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_message.Message) + assert response.name == "name_value" + assert response.text == "text_value" + assert response.formatted_text == "formatted_text_value" + assert response.fallback_text == "fallback_text_value" + assert response.argument_text == "argument_text_value" + assert response.thread_reply is True + assert response.client_assigned_message_id == "client_assigned_message_id_value" + + +@pytest.mark.asyncio +async def test_update_message_async_from_dict(): + await test_update_message_async(request_type=dict) + + +def test_update_message_field_headers(): + client = ChatServiceClient( + 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 = gc_message.UpdateMessageRequest() + + request.message.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_message), "__call__") as call: + call.return_value = gc_message.Message() + client.update_message(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.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_message_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = gc_message.UpdateMessageRequest() + + request.message.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_message), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_message.Message()) + await client.update_message(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.name=name_value", + ) in kw["metadata"] + + +def test_update_message_flattened(): + client = ChatServiceClient( + 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), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_message.Message() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_message( + message=gc_message.Message(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].message + mock_val = gc_message.Message(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_message_flattened_error(): + client = ChatServiceClient( + 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_message( + gc_message.UpdateMessageRequest(), + message=gc_message.Message(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_message_flattened_async(): + client = ChatServiceAsyncClient( + 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), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_message.Message() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_message.Message()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_message( + message=gc_message.Message(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 + mock_val = gc_message.Message(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_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_message( + gc_message.UpdateMessageRequest(), + message=gc_message.Message(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + message.DeleteMessageRequest, + dict, + ], +) +def test_delete_message(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == message.DeleteMessageRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_message_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_message), "__call__") as call: + client.delete_message() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == message.DeleteMessageRequest() + + +@pytest.mark.asyncio +async def test_delete_message_async( + transport: str = "grpc_asyncio", request_type=message.DeleteMessageRequest +): + client = ChatServiceAsyncClient( + 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), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == message.DeleteMessageRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_message_async_from_dict(): + await test_delete_message_async(request_type=dict) + + +def test_delete_message_field_headers(): + client = ChatServiceClient( + 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 = message.DeleteMessageRequest() + + 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), "__call__") as call: + call.return_value = None + client.delete_message(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_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = message.DeleteMessageRequest() + + 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), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_message(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_message_flattened(): + client = ChatServiceClient( + 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), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_message( + 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_delete_message_flattened_error(): + client = ChatServiceClient( + 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_message( + message.DeleteMessageRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_message_flattened_async(): + client = ChatServiceAsyncClient( + 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), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_message( + 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_message_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_message( + message.DeleteMessageRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + attachment.GetAttachmentRequest, + dict, + ], +) +def test_get_attachment(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_attachment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = attachment.Attachment( + name="name_value", + content_name="content_name_value", + content_type="content_type_value", + thumbnail_uri="thumbnail_uri_value", + download_uri="download_uri_value", + source=attachment.Attachment.Source.DRIVE_FILE, + ) + response = client.get_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == attachment.GetAttachmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, attachment.Attachment) + assert response.name == "name_value" + assert response.content_name == "content_name_value" + assert response.content_type == "content_type_value" + assert response.thumbnail_uri == "thumbnail_uri_value" + assert response.download_uri == "download_uri_value" + assert response.source == attachment.Attachment.Source.DRIVE_FILE + + +def test_get_attachment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_attachment), "__call__") as call: + client.get_attachment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attachment.GetAttachmentRequest() + + +@pytest.mark.asyncio +async def test_get_attachment_async( + transport: str = "grpc_asyncio", request_type=attachment.GetAttachmentRequest +): + client = ChatServiceAsyncClient( + 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_attachment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + attachment.Attachment( + name="name_value", + content_name="content_name_value", + content_type="content_type_value", + thumbnail_uri="thumbnail_uri_value", + download_uri="download_uri_value", + source=attachment.Attachment.Source.DRIVE_FILE, + ) + ) + response = await client.get_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == attachment.GetAttachmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, attachment.Attachment) + assert response.name == "name_value" + assert response.content_name == "content_name_value" + assert response.content_type == "content_type_value" + assert response.thumbnail_uri == "thumbnail_uri_value" + assert response.download_uri == "download_uri_value" + assert response.source == attachment.Attachment.Source.DRIVE_FILE + + +@pytest.mark.asyncio +async def test_get_attachment_async_from_dict(): + await test_get_attachment_async(request_type=dict) + + +def test_get_attachment_field_headers(): + client = ChatServiceClient( + 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 = attachment.GetAttachmentRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_attachment), "__call__") as call: + call.return_value = attachment.Attachment() + client.get_attachment(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_attachment_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = attachment.GetAttachmentRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_attachment), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + attachment.Attachment() + ) + await client.get_attachment(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_attachment_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_attachment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = attachment.Attachment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_attachment( + 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_attachment_flattened_error(): + client = ChatServiceClient( + 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_attachment( + attachment.GetAttachmentRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_attachment_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_attachment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = attachment.Attachment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + attachment.Attachment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_attachment( + 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_attachment_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_attachment( + attachment.GetAttachmentRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + attachment.UploadAttachmentRequest, + dict, + ], +) +def test_upload_attachment(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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.upload_attachment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = attachment.UploadAttachmentResponse() + response = client.upload_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == attachment.UploadAttachmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, attachment.UploadAttachmentResponse) + + +def test_upload_attachment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_attachment), "__call__" + ) as call: + client.upload_attachment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == attachment.UploadAttachmentRequest() + + +@pytest.mark.asyncio +async def test_upload_attachment_async( + transport: str = "grpc_asyncio", request_type=attachment.UploadAttachmentRequest +): + client = ChatServiceAsyncClient( + 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.upload_attachment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + attachment.UploadAttachmentResponse() + ) + response = await client.upload_attachment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == attachment.UploadAttachmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, attachment.UploadAttachmentResponse) + + +@pytest.mark.asyncio +async def test_upload_attachment_async_from_dict(): + await test_upload_attachment_async(request_type=dict) + + +def test_upload_attachment_field_headers(): + client = ChatServiceClient( + 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 = attachment.UploadAttachmentRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_attachment), "__call__" + ) as call: + call.return_value = attachment.UploadAttachmentResponse() + client.upload_attachment(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_upload_attachment_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = attachment.UploadAttachmentRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_attachment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + attachment.UploadAttachmentResponse() + ) + await client.upload_attachment(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"] + + +@pytest.mark.parametrize( + "request_type", + [ + space.ListSpacesRequest, + dict, + ], +) +def test_list_spaces(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_spaces), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = space.ListSpacesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_spaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == space.ListSpacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSpacesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_spaces_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_spaces), "__call__") as call: + client.list_spaces() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.ListSpacesRequest() + + +@pytest.mark.asyncio +async def test_list_spaces_async( + transport: str = "grpc_asyncio", request_type=space.ListSpacesRequest +): + client = ChatServiceAsyncClient( + 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_spaces), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space.ListSpacesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_spaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == space.ListSpacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSpacesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_spaces_async_from_dict(): + await test_list_spaces_async(request_type=dict) + + +def test_list_spaces_pager(transport_name: str = "grpc"): + client = ChatServiceClient( + 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_spaces), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + space.Space(), + ], + next_page_token="abc", + ), + space.ListSpacesResponse( + spaces=[], + next_page_token="def", + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + ], + next_page_token="ghi", + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.list_spaces(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, space.Space) for i in results) + + +def test_list_spaces_pages(transport_name: str = "grpc"): + client = ChatServiceClient( + 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_spaces), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + space.Space(), + ], + next_page_token="abc", + ), + space.ListSpacesResponse( + spaces=[], + next_page_token="def", + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + ], + next_page_token="ghi", + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + ], + ), + RuntimeError, + ) + pages = list(client.list_spaces(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_spaces_async_pager(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_spaces), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + space.Space(), + ], + next_page_token="abc", + ), + space.ListSpacesResponse( + spaces=[], + next_page_token="def", + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + ], + next_page_token="ghi", + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_spaces( + 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, space.Space) for i in responses) + + +@pytest.mark.asyncio +async def test_list_spaces_async_pages(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_spaces), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + space.Space(), + ], + next_page_token="abc", + ), + space.ListSpacesResponse( + spaces=[], + next_page_token="def", + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + ], + next_page_token="ghi", + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + ], + ), + 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_spaces(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", + [ + space.GetSpaceRequest, + dict, + ], +) +def test_get_space(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = space.Space( + name="name_value", + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + response = client.get_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == space.GetSpaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == "name_value" + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_get_space_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_space), "__call__") as call: + client.get_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.GetSpaceRequest() + + +@pytest.mark.asyncio +async def test_get_space_async( + transport: str = "grpc_asyncio", request_type=space.GetSpaceRequest +): + client = ChatServiceAsyncClient( + 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_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space.Space( + name="name_value", + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + ) + response = await client.get_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == space.GetSpaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == "name_value" + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +@pytest.mark.asyncio +async def test_get_space_async_from_dict(): + await test_get_space_async(request_type=dict) + + +def test_get_space_field_headers(): + client = ChatServiceClient( + 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 = space.GetSpaceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_space), "__call__") as call: + call.return_value = space.Space() + client.get_space(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_space_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = space.GetSpaceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_space), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(space.Space()) + await client.get_space(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_space_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = space.Space() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_space( + 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_space_flattened_error(): + client = ChatServiceClient( + 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_space( + space.GetSpaceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_space_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = space.Space() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(space.Space()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_space( + 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_space_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_space( + space.GetSpaceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_space.CreateSpaceRequest, + dict, + ], +) +def test_create_space(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space.Space( + name="name_value", + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + response = client.create_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gc_space.CreateSpaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_space.Space) + assert response.name == "name_value" + assert response.type_ == gc_space.Space.Type.ROOM + assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_create_space_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_space), "__call__") as call: + client.create_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_space.CreateSpaceRequest() + + +@pytest.mark.asyncio +async def test_create_space_async( + transport: str = "grpc_asyncio", request_type=gc_space.CreateSpaceRequest +): + client = ChatServiceAsyncClient( + 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_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_space.Space( + name="name_value", + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + ) + response = await client.create_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gc_space.CreateSpaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_space.Space) + assert response.name == "name_value" + assert response.type_ == gc_space.Space.Type.ROOM + assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +@pytest.mark.asyncio +async def test_create_space_async_from_dict(): + await test_create_space_async(request_type=dict) + + +def test_create_space_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space.Space() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_space( + space=gc_space.Space(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].space + mock_val = gc_space.Space(name="name_value") + assert arg == mock_val + + +def test_create_space_flattened_error(): + client = ChatServiceClient( + 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_space( + gc_space.CreateSpaceRequest(), + space=gc_space.Space(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_space_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space.Space() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_space.Space()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_space( + space=gc_space.Space(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].space + mock_val = gc_space.Space(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_space_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_space( + gc_space.CreateSpaceRequest(), + space=gc_space.Space(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + space_setup.SetUpSpaceRequest, + dict, + ], +) +def test_set_up_space(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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.set_up_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = space.Space( + name="name_value", + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + response = client.set_up_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == space_setup.SetUpSpaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == "name_value" + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_set_up_space_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_up_space), "__call__") as call: + client.set_up_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space_setup.SetUpSpaceRequest() + + +@pytest.mark.asyncio +async def test_set_up_space_async( + transport: str = "grpc_asyncio", request_type=space_setup.SetUpSpaceRequest +): + client = ChatServiceAsyncClient( + 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.set_up_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space.Space( + name="name_value", + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + ) + response = await client.set_up_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == space_setup.SetUpSpaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == "name_value" + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +@pytest.mark.asyncio +async def test_set_up_space_async_from_dict(): + await test_set_up_space_async(request_type=dict) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_space.UpdateSpaceRequest, + dict, + ], +) +def test_update_space(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space.Space( + name="name_value", + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + response = client.update_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gc_space.UpdateSpaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_space.Space) + assert response.name == "name_value" + assert response.type_ == gc_space.Space.Type.ROOM + assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_update_space_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_space), "__call__") as call: + client.update_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_space.UpdateSpaceRequest() + + +@pytest.mark.asyncio +async def test_update_space_async( + transport: str = "grpc_asyncio", request_type=gc_space.UpdateSpaceRequest +): + client = ChatServiceAsyncClient( + 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_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_space.Space( + name="name_value", + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + ) + response = await client.update_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gc_space.UpdateSpaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_space.Space) + assert response.name == "name_value" + assert response.type_ == gc_space.Space.Type.ROOM + assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +@pytest.mark.asyncio +async def test_update_space_async_from_dict(): + await test_update_space_async(request_type=dict) + + +def test_update_space_field_headers(): + client = ChatServiceClient( + 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 = gc_space.UpdateSpaceRequest() + + request.space.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_space), "__call__") as call: + call.return_value = gc_space.Space() + client.update_space(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", + "space.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_space_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = gc_space.UpdateSpaceRequest() + + request.space.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_space), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_space.Space()) + await client.update_space(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", + "space.name=name_value", + ) in kw["metadata"] + + +def test_update_space_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space.Space() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_space( + space=gc_space.Space(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].space + mock_val = gc_space.Space(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_space_flattened_error(): + client = ChatServiceClient( + 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_space( + gc_space.UpdateSpaceRequest(), + space=gc_space.Space(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_space_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_space.Space() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gc_space.Space()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_space( + space=gc_space.Space(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].space + mock_val = gc_space.Space(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_space_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_space( + gc_space.UpdateSpaceRequest(), + space=gc_space.Space(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + space.DeleteSpaceRequest, + dict, + ], +) +def test_delete_space(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == space.DeleteSpaceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_space_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_space), "__call__") as call: + client.delete_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.DeleteSpaceRequest() + + +@pytest.mark.asyncio +async def test_delete_space_async( + transport: str = "grpc_asyncio", request_type=space.DeleteSpaceRequest +): + client = ChatServiceAsyncClient( + 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_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == space.DeleteSpaceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_space_async_from_dict(): + await test_delete_space_async(request_type=dict) + + +def test_delete_space_field_headers(): + client = ChatServiceClient( + 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 = space.DeleteSpaceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_space), "__call__") as call: + call.return_value = None + client.delete_space(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_space_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = space.DeleteSpaceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_space), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_space(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_space_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_space( + 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_delete_space_flattened_error(): + client = ChatServiceClient( + 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_space( + space.DeleteSpaceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_space_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_space), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_space( + 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_space_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_space( + space.DeleteSpaceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + space.CompleteImportSpaceRequest, + dict, + ], +) +def test_complete_import_space(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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.complete_import_space), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = space.CompleteImportSpaceResponse() + response = client.complete_import_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == space.CompleteImportSpaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, space.CompleteImportSpaceResponse) + + +def test_complete_import_space_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_import_space), "__call__" + ) as call: + client.complete_import_space() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.CompleteImportSpaceRequest() + + +@pytest.mark.asyncio +async def test_complete_import_space_async( + transport: str = "grpc_asyncio", request_type=space.CompleteImportSpaceRequest +): + client = ChatServiceAsyncClient( + 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.complete_import_space), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space.CompleteImportSpaceResponse() + ) + response = await client.complete_import_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == space.CompleteImportSpaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, space.CompleteImportSpaceResponse) + + +@pytest.mark.asyncio +async def test_complete_import_space_async_from_dict(): + await test_complete_import_space_async(request_type=dict) + + +def test_complete_import_space_field_headers(): + client = ChatServiceClient( + 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 = space.CompleteImportSpaceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_import_space), "__call__" + ) as call: + call.return_value = space.CompleteImportSpaceResponse() + client.complete_import_space(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_complete_import_space_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = space.CompleteImportSpaceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_import_space), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space.CompleteImportSpaceResponse() + ) + await client.complete_import_space(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"] + + +@pytest.mark.parametrize( + "request_type", + [ + space.FindDirectMessageRequest, + dict, + ], +) +def test_find_direct_message(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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.find_direct_message), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = space.Space( + name="name_value", + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + response = client.find_direct_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == space.FindDirectMessageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == "name_value" + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_find_direct_message_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_direct_message), "__call__" + ) as call: + client.find_direct_message() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == space.FindDirectMessageRequest() + + +@pytest.mark.asyncio +async def test_find_direct_message_async( + transport: str = "grpc_asyncio", request_type=space.FindDirectMessageRequest +): + client = ChatServiceAsyncClient( + 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.find_direct_message), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + space.Space( + name="name_value", + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + ) + response = await client.find_direct_message(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == space.FindDirectMessageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == "name_value" + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +@pytest.mark.asyncio +async def test_find_direct_message_async_from_dict(): + await test_find_direct_message_async(request_type=dict) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_membership.CreateMembershipRequest, + dict, + ], +) +def test_create_membership(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_membership), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gc_membership.Membership( + name="name_value", + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, + ) + response = client.create_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gc_membership.CreateMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_membership.Membership) + assert response.name == "name_value" + assert response.state == gc_membership.Membership.MembershipState.JOINED + assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER + + +def test_create_membership_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), "__call__" + ) as call: + client.create_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_membership.CreateMembershipRequest() + + +@pytest.mark.asyncio +async def test_create_membership_async( + transport: str = "grpc_asyncio", request_type=gc_membership.CreateMembershipRequest +): + client = ChatServiceAsyncClient( + 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_membership), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_membership.Membership( + name="name_value", + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, + ) + ) + response = await client.create_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gc_membership.CreateMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_membership.Membership) + assert response.name == "name_value" + assert response.state == gc_membership.Membership.MembershipState.JOINED + assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER + + +@pytest.mark.asyncio +async def test_create_membership_async_from_dict(): + await test_create_membership_async(request_type=dict) + + +def test_create_membership_field_headers(): + client = ChatServiceClient( + 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 = gc_membership.CreateMembershipRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), "__call__" + ) as call: + call.return_value = gc_membership.Membership() + client.create_membership(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_membership_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = gc_membership.CreateMembershipRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_membership.Membership() + ) + await client.create_membership(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_membership_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gc_membership.Membership() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_membership( + parent="parent_value", + membership=gc_membership.Membership(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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].membership + mock_val = gc_membership.Membership(name="name_value") + assert arg == mock_val + + +def test_create_membership_flattened_error(): + client = ChatServiceClient( + 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_membership( + gc_membership.CreateMembershipRequest(), + parent="parent_value", + membership=gc_membership.Membership(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_membership_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gc_membership.Membership() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_membership.Membership() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_membership( + parent="parent_value", + membership=gc_membership.Membership(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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].membership + mock_val = gc_membership.Membership(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_membership_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_membership( + gc_membership.CreateMembershipRequest(), + parent="parent_value", + membership=gc_membership.Membership(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + membership.DeleteMembershipRequest, + dict, + ], +) +def test_delete_membership(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_membership), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership( + name="name_value", + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + ) + response = client.delete_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == membership.DeleteMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == "name_value" + assert response.state == membership.Membership.MembershipState.JOINED + assert response.role == membership.Membership.MembershipRole.ROLE_MEMBER + + +def test_delete_membership_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: + client.delete_membership() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == membership.DeleteMembershipRequest() + + +@pytest.mark.asyncio +async def test_delete_membership_async( + transport: str = "grpc_asyncio", request_type=membership.DeleteMembershipRequest +): + client = ChatServiceAsyncClient( + 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_membership), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + membership.Membership( + name="name_value", + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + ) + ) + response = await client.delete_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == membership.DeleteMembershipRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == "name_value" + assert response.state == membership.Membership.MembershipState.JOINED + assert response.role == membership.Membership.MembershipRole.ROLE_MEMBER + + +@pytest.mark.asyncio +async def test_delete_membership_async_from_dict(): + await test_delete_membership_async(request_type=dict) + + +def test_delete_membership_field_headers(): + client = ChatServiceClient( + 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 = membership.DeleteMembershipRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: + call.return_value = membership.Membership() + client.delete_membership(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_membership_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = membership.DeleteMembershipRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + membership.Membership() + ) + await client.delete_membership(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_membership_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_membership( + 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_delete_membership_flattened_error(): + client = ChatServiceClient( + 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_membership( + membership.DeleteMembershipRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_membership_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + membership.Membership() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_membership( + 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_membership_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_membership( + membership.DeleteMembershipRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_reaction.CreateReactionRequest, + dict, + ], +) +def test_create_reaction(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_reaction), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_reaction.Reaction( + name="name_value", + ) + response = client.create_reaction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gc_reaction.CreateReactionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_reaction.Reaction) + assert response.name == "name_value" + + +def test_create_reaction_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_reaction), "__call__") as call: + client.create_reaction() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gc_reaction.CreateReactionRequest() + + +@pytest.mark.asyncio +async def test_create_reaction_async( + transport: str = "grpc_asyncio", request_type=gc_reaction.CreateReactionRequest +): + client = ChatServiceAsyncClient( + 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_reaction), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_reaction.Reaction( + name="name_value", + ) + ) + response = await client.create_reaction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gc_reaction.CreateReactionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_reaction.Reaction) + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_create_reaction_async_from_dict(): + await test_create_reaction_async(request_type=dict) + + +def test_create_reaction_field_headers(): + client = ChatServiceClient( + 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 = gc_reaction.CreateReactionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_reaction), "__call__") as call: + call.return_value = gc_reaction.Reaction() + client.create_reaction(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_reaction_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = gc_reaction.CreateReactionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_reaction), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_reaction.Reaction() + ) + await client.create_reaction(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_reaction_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_reaction), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_reaction.Reaction() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_reaction( + parent="parent_value", + reaction=gc_reaction.Reaction(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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].reaction + mock_val = gc_reaction.Reaction(name="name_value") + assert arg == mock_val + + +def test_create_reaction_flattened_error(): + client = ChatServiceClient( + 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_reaction( + gc_reaction.CreateReactionRequest(), + parent="parent_value", + reaction=gc_reaction.Reaction(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_reaction_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_reaction), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gc_reaction.Reaction() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gc_reaction.Reaction() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_reaction( + parent="parent_value", + reaction=gc_reaction.Reaction(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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].reaction + mock_val = gc_reaction.Reaction(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_reaction_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_reaction( + gc_reaction.CreateReactionRequest(), + parent="parent_value", + reaction=gc_reaction.Reaction(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reaction.ListReactionsRequest, + dict, + ], +) +def test_list_reactions(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_reactions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = reaction.ListReactionsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_reactions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == reaction.ListReactionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReactionsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_reactions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_reactions), "__call__") as call: + client.list_reactions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reaction.ListReactionsRequest() + + +@pytest.mark.asyncio +async def test_list_reactions_async( + transport: str = "grpc_asyncio", request_type=reaction.ListReactionsRequest +): + client = ChatServiceAsyncClient( + 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_reactions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reaction.ListReactionsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_reactions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == reaction.ListReactionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReactionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_reactions_async_from_dict(): + await test_list_reactions_async(request_type=dict) + + +def test_list_reactions_field_headers(): + client = ChatServiceClient( + 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 = reaction.ListReactionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_reactions), "__call__") as call: + call.return_value = reaction.ListReactionsResponse() + client.list_reactions(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_reactions_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = reaction.ListReactionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_reactions), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reaction.ListReactionsResponse() + ) + await client.list_reactions(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_reactions_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_reactions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = reaction.ListReactionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_reactions( + 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_reactions_flattened_error(): + client = ChatServiceClient( + 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_reactions( + reaction.ListReactionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_reactions_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_reactions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = reaction.ListReactionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + reaction.ListReactionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_reactions( + 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_reactions_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_reactions( + reaction.ListReactionsRequest(), + parent="parent_value", + ) + + +def test_list_reactions_pager(transport_name: str = "grpc"): + client = ChatServiceClient( + 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_reactions), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + reaction.Reaction(), + ], + next_page_token="abc", + ), + reaction.ListReactionsResponse( + reactions=[], + next_page_token="def", + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + ], + next_page_token="ghi", + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_reactions(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, reaction.Reaction) for i in results) + + +def test_list_reactions_pages(transport_name: str = "grpc"): + client = ChatServiceClient( + 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_reactions), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + reaction.Reaction(), + ], + next_page_token="abc", + ), + reaction.ListReactionsResponse( + reactions=[], + next_page_token="def", + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + ], + next_page_token="ghi", + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + ], + ), + RuntimeError, + ) + pages = list(client.list_reactions(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_reactions_async_pager(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_reactions), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + reaction.Reaction(), + ], + next_page_token="abc", + ), + reaction.ListReactionsResponse( + reactions=[], + next_page_token="def", + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + ], + next_page_token="ghi", + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_reactions( + 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, reaction.Reaction) for i in responses) + + +@pytest.mark.asyncio +async def test_list_reactions_async_pages(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_reactions), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + reaction.Reaction(), + ], + next_page_token="abc", + ), + reaction.ListReactionsResponse( + reactions=[], + next_page_token="def", + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + ], + next_page_token="ghi", + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + ], + ), + 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_reactions(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", + [ + reaction.DeleteReactionRequest, + dict, + ], +) +def test_delete_reaction(request_type, transport: str = "grpc"): + client = ChatServiceClient( + 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_reaction), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_reaction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == reaction.DeleteReactionRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_reaction_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_reaction), "__call__") as call: + client.delete_reaction() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == reaction.DeleteReactionRequest() + + +@pytest.mark.asyncio +async def test_delete_reaction_async( + transport: str = "grpc_asyncio", request_type=reaction.DeleteReactionRequest +): + client = ChatServiceAsyncClient( + 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_reaction), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_reaction(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == reaction.DeleteReactionRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_reaction_async_from_dict(): + await test_delete_reaction_async(request_type=dict) + + +def test_delete_reaction_field_headers(): + client = ChatServiceClient( + 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 = reaction.DeleteReactionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_reaction), "__call__") as call: + call.return_value = None + client.delete_reaction(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_reaction_field_headers_async(): + client = ChatServiceAsyncClient( + 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 = reaction.DeleteReactionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_reaction), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_reaction(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_reaction_flattened(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_reaction), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_reaction( + 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_delete_reaction_flattened_error(): + client = ChatServiceClient( + 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_reaction( + reaction.DeleteReactionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_reaction_flattened_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_reaction), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_reaction( + 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_reaction_flattened_error_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_reaction( + reaction.DeleteReactionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_message.CreateMessageRequest, + dict, + ], +) +def test_create_message_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request_init["message"] = { + "name": "name_value", + "sender": { + "name": "name_value", + "display_name": "display_name_value", + "domain_id": "domain_id_value", + "type_": 1, + "is_anonymous": True, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "last_update_time": {}, + "delete_time": {}, + "text": "text_value", + "formatted_text": "formatted_text_value", + "cards": [ + { + "header": { + "title": "title_value", + "subtitle": "subtitle_value", + "image_style": 1, + "image_url": "image_url_value", + }, + "sections": [ + { + "header": "header_value", + "widgets": [ + { + "text_paragraph": {"text": "text_value"}, + "image": { + "image_url": "image_url_value", + "on_click": { + "action": { + "action_method_name": "action_method_name_value", + "parameters": [ + { + "key": "key_value", + "value": "value_value", + } + ], + }, + "open_link": {"url": "url_value"}, + }, + "aspect_ratio": 0.1278, + }, + "key_value": { + "icon": 1, + "icon_url": "icon_url_value", + "top_label": "top_label_value", + "content": "content_value", + "content_multiline": True, + "bottom_label": "bottom_label_value", + "on_click": {}, + "button": { + "text_button": { + "text": "text_value", + "on_click": {}, + }, + "image_button": { + "icon": 1, + "icon_url": "icon_url_value", + "on_click": {}, + "name": "name_value", + }, + }, + }, + "buttons": {}, + } + ], + } + ], + "card_actions": [ + {"action_label": "action_label_value", "on_click": {}} + ], + "name": "name_value", + } + ], + "cards_v2": [ + { + "card_id": "card_id_value", + "card": { + "header": { + "title": "title_value", + "subtitle": "subtitle_value", + "image_type": 1, + "image_url": "image_url_value", + "image_alt_text": "image_alt_text_value", + }, + "sections": [ + { + "header": "header_value", + "widgets": [ + { + "text_paragraph": {"text": "text_value"}, + "image": { + "image_url": "image_url_value", + "on_click": { + "action": { + "function": "function_value", + "parameters": [ + { + "key": "key_value", + "value": "value_value", + } + ], + "load_indicator": 1, + "persist_values": True, + "interaction": 1, + }, + "open_link": { + "url": "url_value", + "open_as": 1, + "on_close": 1, + }, + "open_dynamic_link_action": {}, + "card": {}, + }, + "alt_text": "alt_text_value", + }, + "decorated_text": { + "icon": { + "known_icon": "known_icon_value", + "icon_url": "icon_url_value", + "alt_text": "alt_text_value", + "image_type": 1, + }, + "start_icon": {}, + "top_label": "top_label_value", + "text": "text_value", + "wrap_text": True, + "bottom_label": "bottom_label_value", + "on_click": {}, + "button": { + "text": "text_value", + "icon": {}, + "color": { + "red": 0.315, + "green": 0.529, + "blue": 0.424, + "alpha": {"value": 0.541}, + }, + "on_click": {}, + "disabled": True, + "alt_text": "alt_text_value", + }, + "switch_control": { + "name": "name_value", + "value": "value_value", + "selected": True, + "on_change_action": {}, + "control_type": 1, + }, + "end_icon": {}, + }, + "button_list": {"buttons": {}}, + "text_input": { + "name": "name_value", + "label": "label_value", + "hint_text": "hint_text_value", + "value": "value_value", + "type_": 1, + "on_change_action": {}, + "initial_suggestions": { + "items": [{"text": "text_value"}] + }, + "auto_complete_action": {}, + "placeholder_text": "placeholder_text_value", + }, + "selection_input": { + "name": "name_value", + "label": "label_value", + "type_": 1, + "items": [ + { + "text": "text_value", + "value": "value_value", + "selected": True, + "start_icon_uri": "start_icon_uri_value", + "bottom_text": "bottom_text_value", + } + ], + "on_change_action": {}, + "multi_select_max_selected_items": 3288, + "multi_select_min_query_length": 3107, + "external_data_source": {}, + "platform_data_source": { + "common_data_source": 1 + }, + }, + "date_time_picker": { + "name": "name_value", + "label": "label_value", + "type_": 1, + "value_ms_epoch": 1482, + "timezone_offset_date": 2126, + "on_change_action": {}, + }, + "divider": {}, + "grid": { + "title": "title_value", + "items": [ + { + "id": "id_value", + "image": { + "image_uri": "image_uri_value", + "alt_text": "alt_text_value", + "crop_style": { + "type_": 1, + "aspect_ratio": 0.1278, + }, + "border_style": { + "type_": 1, + "stroke_color": {}, + "corner_radius": 1392, + }, + }, + "title": "title_value", + "subtitle": "subtitle_value", + "layout": 1, + } + ], + "border_style": {}, + "column_count": 1302, + "on_click": {}, + }, + "columns": { + "column_items": [ + { + "horizontal_size_style": 1, + "horizontal_alignment": 1, + "vertical_alignment": 1, + "widgets": [ + { + "text_paragraph": {}, + "image": {}, + "decorated_text": {}, + "button_list": {}, + "text_input": {}, + "selection_input": {}, + "date_time_picker": {}, + } + ], + } + ] + }, + "horizontal_alignment": 1, + } + ], + "collapsible": True, + "uncollapsible_widgets_count": 2891, + } + ], + "section_divider_style": 1, + "card_actions": [ + {"action_label": "action_label_value", "on_click": {}} + ], + "name": "name_value", + "fixed_footer": {"primary_button": {}, "secondary_button": {}}, + "display_style": 1, + "peek_card_header": {}, + }, + } + ], + "annotations": [ + { + "type_": 1, + "start_index": 1189, + "length": 642, + "user_mention": {"user": {}, "type_": 1}, + "slash_command": { + "bot": {}, + "type_": 1, + "command_name": "command_name_value", + "command_id": 1035, + "triggers_dialog": True, + }, + } + ], + "thread": {"name": "name_value", "thread_key": "thread_key_value"}, + "space": { + "name": "name_value", + "type_": 1, + "space_type": 1, + "single_user_bot_dm": True, + "threaded": True, + "display_name": "display_name_value", + "external_user_allowed": True, + "space_threading_state": 2, + "space_details": { + "description": "description_value", + "guidelines": "guidelines_value", + }, + "space_history_state": 1, + "import_mode": True, + "create_time": {}, + "admin_installed": True, + }, + "fallback_text": "fallback_text_value", + "action_response": { + "type_": 1, + "url": "url_value", + "dialog_action": { + "dialog": {"body": {}}, + "action_status": { + "status_code": 1, + "user_facing_message": "user_facing_message_value", + }, + }, + "updated_widget": {"suggestions": {"items": {}}, "widget": "widget_value"}, + }, + "argument_text": "argument_text_value", + "slash_command": {"command_id": 1035}, + "attachment": [ + { + "name": "name_value", + "content_name": "content_name_value", + "content_type": "content_type_value", + "attachment_data_ref": { + "resource_name": "resource_name_value", + "attachment_upload_token": "attachment_upload_token_value", + }, + "drive_data_ref": {"drive_file_id": "drive_file_id_value"}, + "thumbnail_uri": "thumbnail_uri_value", + "download_uri": "download_uri_value", + "source": 1, + } + ], + "matched_url": {"url": "url_value"}, + "thread_reply": True, + "client_assigned_message_id": "client_assigned_message_id_value", + "emoji_reaction_summaries": [ + { + "emoji": { + "unicode": "unicode_value", + "custom_emoji": {"uid": "uid_value"}, + }, + "reaction_count": 1501, + } + ], + "private_message_viewer": {}, + "deletion_metadata": {"deletion_type": 1}, + "quoted_message_metadata": {"name": "name_value", "last_update_time": {}}, + "attached_gifs": [{"uri": "uri_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 = gc_message.CreateMessageRequest.meta.fields["message"] + + 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"].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"][field])): + del request_init["message"][field][i][subfield] + else: + del request_init["message"][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 = gc_message.Message( + name="name_value", + text="text_value", + formatted_text="formatted_text_value", + fallback_text="fallback_text_value", + argument_text="argument_text_value", + thread_reply=True, + client_assigned_message_id="client_assigned_message_id_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 = gc_message.Message.pb(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.create_message(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_message.Message) + assert response.name == "name_value" + assert response.text == "text_value" + assert response.formatted_text == "formatted_text_value" + assert response.fallback_text == "fallback_text_value" + assert response.argument_text == "argument_text_value" + assert response.thread_reply is True + assert response.client_assigned_message_id == "client_assigned_message_id_value" + + +def test_create_message_rest_required_fields( + request_type=gc_message.CreateMessageRequest, +): + transport_class = transports.ChatServiceRestTransport + + 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() + ).create_message._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() + ).create_message._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "message_id", + "message_reply_option", + "request_id", + "thread_key", + ) + ) + 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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gc_message.Message() + # 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 = gc_message.Message.pb(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.create_message(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_message_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_message._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "messageId", + "messageReplyOption", + "requestId", + "threadKey", + ) + ) + & set( + ( + "parent", + "message", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_message_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_create_message" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_create_message" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gc_message.CreateMessageRequest.pb( + gc_message.CreateMessageRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gc_message.Message.to_json(gc_message.Message()) + + request = gc_message.CreateMessageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gc_message.Message() + + client.create_message( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_message_rest_bad_request( + transport: str = "rest", request_type=gc_message.CreateMessageRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_message(request) + + +def test_create_message_rest_flattened(): + client = ChatServiceClient( + 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 = gc_message.Message() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "spaces/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + message=gc_message.Message(name="name_value"), + message_id="message_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 = gc_message.Message.pb(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.create_message(**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=spaces/*}/messages" % client.transport._host, args[1] + ) + + +def test_create_message_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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( + gc_message.CreateMessageRequest(), + parent="parent_value", + message=gc_message.Message(name="name_value"), + message_id="message_id_value", + ) + + +def test_create_message_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + message.ListMessagesRequest, + dict, + ], +) +def test_list_messages_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = message.ListMessagesResponse( + next_page_token="next_page_token_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 = message.ListMessagesResponse.pb(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_messages(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMessagesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_messages_rest_required_fields(request_type=message.ListMessagesRequest): + transport_class = transports.ChatServiceRestTransport + + 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_messages._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_messages._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", + "show_deleted", + ) + ) + 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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = message.ListMessagesResponse() + # 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.ListMessagesResponse.pb(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_messages(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_messages_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_messages._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "showDeleted", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_messages_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_list_messages" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_list_messages" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = message.ListMessagesRequest.pb(message.ListMessagesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = message.ListMessagesResponse.to_json( + message.ListMessagesResponse() + ) + + request = message.ListMessagesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = message.ListMessagesResponse() + + client.list_messages( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_messages_rest_bad_request( + transport: str = "rest", request_type=message.ListMessagesRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_messages(request) + + +def test_list_messages_rest_flattened(): + client = ChatServiceClient( + 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.ListMessagesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "spaces/sample1"} + + # 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 = message.ListMessagesResponse.pb(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_messages(**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=spaces/*}/messages" % client.transport._host, args[1] + ) + + +def test_list_messages_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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_messages( + message.ListMessagesRequest(), + parent="parent_value", + ) + + +def test_list_messages_rest_pager(transport: str = "rest"): + client = ChatServiceClient( + 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 = ( + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + message.Message(), + ], + next_page_token="abc", + ), + message.ListMessagesResponse( + messages=[], + next_page_token="def", + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + ], + next_page_token="ghi", + ), + message.ListMessagesResponse( + messages=[ + message.Message(), + message.Message(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(message.ListMessagesResponse.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": "spaces/sample1"} + + pager = client.list_messages(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, message.Message) for i in results) + + pages = list(client.list_messages(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + membership.ListMembershipsRequest, + dict, + ], +) +def test_list_memberships_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = membership.ListMembershipsResponse( + next_page_token="next_page_token_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 = membership.ListMembershipsResponse.pb(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_memberships(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_memberships_rest_required_fields( + request_type=membership.ListMembershipsRequest, +): + transport_class = transports.ChatServiceRestTransport + + 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_memberships._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_memberships._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + "show_groups", + "show_invited", + ) + ) + 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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.ListMembershipsResponse() + # 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 = membership.ListMembershipsResponse.pb(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_memberships(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_memberships_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_memberships._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + "showGroups", + "showInvited", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_memberships_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_list_memberships" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_list_memberships" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.ListMembershipsRequest.pb( + membership.ListMembershipsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = membership.ListMembershipsResponse.to_json( + membership.ListMembershipsResponse() + ) + + request = membership.ListMembershipsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.ListMembershipsResponse() + + client.list_memberships( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_memberships_rest_bad_request( + transport: str = "rest", request_type=membership.ListMembershipsRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_memberships(request) + + +def test_list_memberships_rest_flattened(): + client = ChatServiceClient( + 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 = membership.ListMembershipsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "spaces/sample1"} + + # 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 = membership.ListMembershipsResponse.pb(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_memberships(**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=spaces/*}/members" % client.transport._host, args[1] + ) + + +def test_list_memberships_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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_memberships( + membership.ListMembershipsRequest(), + parent="parent_value", + ) + + +def test_list_memberships_rest_pager(transport: str = "rest"): + client = ChatServiceClient( + 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 = ( + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token="abc", + ), + membership.ListMembershipsResponse( + memberships=[], + next_page_token="def", + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + ], + next_page_token="ghi", + ), + membership.ListMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + membership.ListMembershipsResponse.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": "spaces/sample1"} + + pager = client.list_memberships(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, membership.Membership) for i in results) + + pages = list(client.list_memberships(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + membership.GetMembershipRequest, + dict, + ], +) +def test_get_membership_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/members/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 = membership.Membership( + name="name_value", + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.Membership.pb(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_membership(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == "name_value" + assert response.state == membership.Membership.MembershipState.JOINED + assert response.role == membership.Membership.MembershipRole.ROLE_MEMBER + + +def test_get_membership_rest_required_fields( + request_type=membership.GetMembershipRequest, +): + transport_class = transports.ChatServiceRestTransport + + 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_membership._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_membership._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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.Membership() + # 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 = membership.Membership.pb(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_membership(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_membership_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_membership_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_get_membership" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_get_membership" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.GetMembershipRequest.pb( + membership.GetMembershipRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = membership.Membership.to_json( + membership.Membership() + ) + + request = membership.GetMembershipRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.Membership() + + client.get_membership( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_membership_rest_bad_request( + transport: str = "rest", request_type=membership.GetMembershipRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/members/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_membership(request) + + +def test_get_membership_rest_flattened(): + client = ChatServiceClient( + 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 = membership.Membership() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1/members/sample2"} + + # 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 = membership.Membership.pb(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_membership(**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=spaces/*/members/*}" % client.transport._host, args[1] + ) + + +def test_get_membership_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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_membership( + membership.GetMembershipRequest(), + name="name_value", + ) + + +def test_get_membership_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + message.GetMessageRequest, + dict, + ], +) +def test_get_message_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/messages/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 = message.Message( + name="name_value", + text="text_value", + formatted_text="formatted_text_value", + fallback_text="fallback_text_value", + argument_text="argument_text_value", + thread_reply=True, + client_assigned_message_id="client_assigned_message_id_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 = message.Message.pb(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(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, message.Message) + assert response.name == "name_value" + assert response.text == "text_value" + assert response.formatted_text == "formatted_text_value" + assert response.fallback_text == "fallback_text_value" + assert response.argument_text == "argument_text_value" + assert response.thread_reply is True + assert response.client_assigned_message_id == "client_assigned_message_id_value" + + +def test_get_message_rest_required_fields(request_type=message.GetMessageRequest): + transport_class = transports.ChatServiceRestTransport + + 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._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._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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = message.Message() + # 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.Message.pb(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(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_message_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_message._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_message_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_get_message" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_get_message" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = message.GetMessageRequest.pb(message.GetMessageRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = message.Message.to_json(message.Message()) + + request = message.GetMessageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = message.Message() + + client.get_message( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_message_rest_bad_request( + transport: str = "rest", request_type=message.GetMessageRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/messages/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_message(request) + + +def test_get_message_rest_flattened(): + client = ChatServiceClient( + 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.Message() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1/messages/sample2"} + + # 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.Message.pb(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(**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=spaces/*/messages/*}" % client.transport._host, args[1] + ) + + +def test_get_message_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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( + message.GetMessageRequest(), + name="name_value", + ) + + +def test_get_message_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_message.UpdateMessageRequest, + dict, + ], +) +def test_update_message_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"message": {"name": "spaces/sample1/messages/sample2"}} + request_init["message"] = { + "name": "spaces/sample1/messages/sample2", + "sender": { + "name": "name_value", + "display_name": "display_name_value", + "domain_id": "domain_id_value", + "type_": 1, + "is_anonymous": True, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "last_update_time": {}, + "delete_time": {}, + "text": "text_value", + "formatted_text": "formatted_text_value", + "cards": [ + { + "header": { + "title": "title_value", + "subtitle": "subtitle_value", + "image_style": 1, + "image_url": "image_url_value", + }, + "sections": [ + { + "header": "header_value", + "widgets": [ + { + "text_paragraph": {"text": "text_value"}, + "image": { + "image_url": "image_url_value", + "on_click": { + "action": { + "action_method_name": "action_method_name_value", + "parameters": [ + { + "key": "key_value", + "value": "value_value", + } + ], + }, + "open_link": {"url": "url_value"}, + }, + "aspect_ratio": 0.1278, + }, + "key_value": { + "icon": 1, + "icon_url": "icon_url_value", + "top_label": "top_label_value", + "content": "content_value", + "content_multiline": True, + "bottom_label": "bottom_label_value", + "on_click": {}, + "button": { + "text_button": { + "text": "text_value", + "on_click": {}, + }, + "image_button": { + "icon": 1, + "icon_url": "icon_url_value", + "on_click": {}, + "name": "name_value", + }, + }, + }, + "buttons": {}, + } + ], + } + ], + "card_actions": [ + {"action_label": "action_label_value", "on_click": {}} + ], + "name": "name_value", + } + ], + "cards_v2": [ + { + "card_id": "card_id_value", + "card": { + "header": { + "title": "title_value", + "subtitle": "subtitle_value", + "image_type": 1, + "image_url": "image_url_value", + "image_alt_text": "image_alt_text_value", + }, + "sections": [ + { + "header": "header_value", + "widgets": [ + { + "text_paragraph": {"text": "text_value"}, + "image": { + "image_url": "image_url_value", + "on_click": { + "action": { + "function": "function_value", + "parameters": [ + { + "key": "key_value", + "value": "value_value", + } + ], + "load_indicator": 1, + "persist_values": True, + "interaction": 1, + }, + "open_link": { + "url": "url_value", + "open_as": 1, + "on_close": 1, + }, + "open_dynamic_link_action": {}, + "card": {}, + }, + "alt_text": "alt_text_value", + }, + "decorated_text": { + "icon": { + "known_icon": "known_icon_value", + "icon_url": "icon_url_value", + "alt_text": "alt_text_value", + "image_type": 1, + }, + "start_icon": {}, + "top_label": "top_label_value", + "text": "text_value", + "wrap_text": True, + "bottom_label": "bottom_label_value", + "on_click": {}, + "button": { + "text": "text_value", + "icon": {}, + "color": { + "red": 0.315, + "green": 0.529, + "blue": 0.424, + "alpha": {"value": 0.541}, + }, + "on_click": {}, + "disabled": True, + "alt_text": "alt_text_value", + }, + "switch_control": { + "name": "name_value", + "value": "value_value", + "selected": True, + "on_change_action": {}, + "control_type": 1, + }, + "end_icon": {}, + }, + "button_list": {"buttons": {}}, + "text_input": { + "name": "name_value", + "label": "label_value", + "hint_text": "hint_text_value", + "value": "value_value", + "type_": 1, + "on_change_action": {}, + "initial_suggestions": { + "items": [{"text": "text_value"}] + }, + "auto_complete_action": {}, + "placeholder_text": "placeholder_text_value", + }, + "selection_input": { + "name": "name_value", + "label": "label_value", + "type_": 1, + "items": [ + { + "text": "text_value", + "value": "value_value", + "selected": True, + "start_icon_uri": "start_icon_uri_value", + "bottom_text": "bottom_text_value", + } + ], + "on_change_action": {}, + "multi_select_max_selected_items": 3288, + "multi_select_min_query_length": 3107, + "external_data_source": {}, + "platform_data_source": { + "common_data_source": 1 + }, + }, + "date_time_picker": { + "name": "name_value", + "label": "label_value", + "type_": 1, + "value_ms_epoch": 1482, + "timezone_offset_date": 2126, + "on_change_action": {}, + }, + "divider": {}, + "grid": { + "title": "title_value", + "items": [ + { + "id": "id_value", + "image": { + "image_uri": "image_uri_value", + "alt_text": "alt_text_value", + "crop_style": { + "type_": 1, + "aspect_ratio": 0.1278, + }, + "border_style": { + "type_": 1, + "stroke_color": {}, + "corner_radius": 1392, + }, + }, + "title": "title_value", + "subtitle": "subtitle_value", + "layout": 1, + } + ], + "border_style": {}, + "column_count": 1302, + "on_click": {}, + }, + "columns": { + "column_items": [ + { + "horizontal_size_style": 1, + "horizontal_alignment": 1, + "vertical_alignment": 1, + "widgets": [ + { + "text_paragraph": {}, + "image": {}, + "decorated_text": {}, + "button_list": {}, + "text_input": {}, + "selection_input": {}, + "date_time_picker": {}, + } + ], + } + ] + }, + "horizontal_alignment": 1, + } + ], + "collapsible": True, + "uncollapsible_widgets_count": 2891, + } + ], + "section_divider_style": 1, + "card_actions": [ + {"action_label": "action_label_value", "on_click": {}} + ], + "name": "name_value", + "fixed_footer": {"primary_button": {}, "secondary_button": {}}, + "display_style": 1, + "peek_card_header": {}, + }, + } + ], + "annotations": [ + { + "type_": 1, + "start_index": 1189, + "length": 642, + "user_mention": {"user": {}, "type_": 1}, + "slash_command": { + "bot": {}, + "type_": 1, + "command_name": "command_name_value", + "command_id": 1035, + "triggers_dialog": True, + }, + } + ], + "thread": {"name": "name_value", "thread_key": "thread_key_value"}, + "space": { + "name": "name_value", + "type_": 1, + "space_type": 1, + "single_user_bot_dm": True, + "threaded": True, + "display_name": "display_name_value", + "external_user_allowed": True, + "space_threading_state": 2, + "space_details": { + "description": "description_value", + "guidelines": "guidelines_value", + }, + "space_history_state": 1, + "import_mode": True, + "create_time": {}, + "admin_installed": True, + }, + "fallback_text": "fallback_text_value", + "action_response": { + "type_": 1, + "url": "url_value", + "dialog_action": { + "dialog": {"body": {}}, + "action_status": { + "status_code": 1, + "user_facing_message": "user_facing_message_value", + }, + }, + "updated_widget": {"suggestions": {"items": {}}, "widget": "widget_value"}, + }, + "argument_text": "argument_text_value", + "slash_command": {"command_id": 1035}, + "attachment": [ + { + "name": "name_value", + "content_name": "content_name_value", + "content_type": "content_type_value", + "attachment_data_ref": { + "resource_name": "resource_name_value", + "attachment_upload_token": "attachment_upload_token_value", + }, + "drive_data_ref": {"drive_file_id": "drive_file_id_value"}, + "thumbnail_uri": "thumbnail_uri_value", + "download_uri": "download_uri_value", + "source": 1, + } + ], + "matched_url": {"url": "url_value"}, + "thread_reply": True, + "client_assigned_message_id": "client_assigned_message_id_value", + "emoji_reaction_summaries": [ + { + "emoji": { + "unicode": "unicode_value", + "custom_emoji": {"uid": "uid_value"}, + }, + "reaction_count": 1501, + } + ], + "private_message_viewer": {}, + "deletion_metadata": {"deletion_type": 1}, + "quoted_message_metadata": {"name": "name_value", "last_update_time": {}}, + "attached_gifs": [{"uri": "uri_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 = gc_message.UpdateMessageRequest.meta.fields["message"] + + 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"].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"][field])): + del request_init["message"][field][i][subfield] + else: + del request_init["message"][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 = gc_message.Message( + name="name_value", + text="text_value", + formatted_text="formatted_text_value", + fallback_text="fallback_text_value", + argument_text="argument_text_value", + thread_reply=True, + client_assigned_message_id="client_assigned_message_id_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 = gc_message.Message.pb(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_message(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_message.Message) + assert response.name == "name_value" + assert response.text == "text_value" + assert response.formatted_text == "formatted_text_value" + assert response.fallback_text == "fallback_text_value" + assert response.argument_text == "argument_text_value" + assert response.thread_reply is True + assert response.client_assigned_message_id == "client_assigned_message_id_value" + + +def test_update_message_rest_required_fields( + request_type=gc_message.UpdateMessageRequest, +): + transport_class = transports.ChatServiceRestTransport + + 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._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._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", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gc_message.Message() + # 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": "put", + "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 = gc_message.Message.pb(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_message(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_message_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_message._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "updateMask", + ) + ) + & set(("message",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_message_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_update_message" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_update_message" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gc_message.UpdateMessageRequest.pb( + gc_message.UpdateMessageRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gc_message.Message.to_json(gc_message.Message()) + + request = gc_message.UpdateMessageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gc_message.Message() + + client.update_message( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_message_rest_bad_request( + transport: str = "rest", request_type=gc_message.UpdateMessageRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"message": {"name": "spaces/sample1/messages/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_message(request) + + +def test_update_message_rest_flattened(): + client = ChatServiceClient( + 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 = gc_message.Message() + + # get arguments that satisfy an http rule for this method + sample_request = {"message": {"name": "spaces/sample1/messages/sample2"}} + + # get truthy value for each flattened field + mock_args = dict( + message=gc_message.Message(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 = gc_message.Message.pb(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_message(**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.name=spaces/*/messages/*}" % client.transport._host, args[1] + ) + + +def test_update_message_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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( + gc_message.UpdateMessageRequest(), + message=gc_message.Message(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_message_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + message.DeleteMessageRequest, + dict, + ], +) +def test_delete_message_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/messages/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_message(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_message_rest_required_fields(request_type=message.DeleteMessageRequest): + transport_class = transports.ChatServiceRestTransport + + 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._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._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force",)) + 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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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 = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_message(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_message_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_message._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force",)) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_message_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "pre_delete_message" + ) as pre: + pre.assert_not_called() + pb_message = message.DeleteMessageRequest.pb(message.DeleteMessageRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = message.DeleteMessageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_message( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_message_rest_bad_request( + transport: str = "rest", request_type=message.DeleteMessageRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/messages/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_message(request) + + +def test_delete_message_rest_flattened(): + client = ChatServiceClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1/messages/sample2"} + + # 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 = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_message(**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=spaces/*/messages/*}" % client.transport._host, args[1] + ) + + +def test_delete_message_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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( + message.DeleteMessageRequest(), + name="name_value", + ) + + +def test_delete_message_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + attachment.GetAttachmentRequest, + dict, + ], +) +def test_get_attachment_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/messages/sample2/attachments/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 = attachment.Attachment( + name="name_value", + content_name="content_name_value", + content_type="content_type_value", + thumbnail_uri="thumbnail_uri_value", + download_uri="download_uri_value", + source=attachment.Attachment.Source.DRIVE_FILE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = attachment.Attachment.pb(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_attachment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, attachment.Attachment) + assert response.name == "name_value" + assert response.content_name == "content_name_value" + assert response.content_type == "content_type_value" + assert response.thumbnail_uri == "thumbnail_uri_value" + assert response.download_uri == "download_uri_value" + assert response.source == attachment.Attachment.Source.DRIVE_FILE + + +def test_get_attachment_rest_required_fields( + request_type=attachment.GetAttachmentRequest, +): + transport_class = transports.ChatServiceRestTransport + + 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_attachment._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_attachment._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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = attachment.Attachment() + # 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 = attachment.Attachment.pb(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_attachment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_attachment_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_attachment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_attachment_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_get_attachment" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_get_attachment" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = attachment.GetAttachmentRequest.pb( + attachment.GetAttachmentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = attachment.Attachment.to_json( + attachment.Attachment() + ) + + request = attachment.GetAttachmentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = attachment.Attachment() + + client.get_attachment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_attachment_rest_bad_request( + transport: str = "rest", request_type=attachment.GetAttachmentRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/messages/sample2/attachments/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_attachment(request) + + +def test_get_attachment_rest_flattened(): + client = ChatServiceClient( + 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 = attachment.Attachment() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1/messages/sample2/attachments/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 = attachment.Attachment.pb(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_attachment(**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=spaces/*/messages/*/attachments/*}" % client.transport._host, + args[1], + ) + + +def test_get_attachment_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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_attachment( + attachment.GetAttachmentRequest(), + name="name_value", + ) + + +def test_get_attachment_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + attachment.UploadAttachmentRequest, + dict, + ], +) +def test_upload_attachment_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = attachment.UploadAttachmentResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = attachment.UploadAttachmentResponse.pb(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.upload_attachment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, attachment.UploadAttachmentResponse) + + +def test_upload_attachment_rest_required_fields( + request_type=attachment.UploadAttachmentRequest, +): + transport_class = transports.ChatServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["filename"] = "" + 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() + ).upload_attachment._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" + jsonified_request["filename"] = "filename_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).upload_attachment._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" + assert "filename" in jsonified_request + assert jsonified_request["filename"] == "filename_value" + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = attachment.UploadAttachmentResponse() + # 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 = attachment.UploadAttachmentResponse.pb(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.upload_attachment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_upload_attachment_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.upload_attachment._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "filename", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_upload_attachment_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_upload_attachment" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_upload_attachment" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = attachment.UploadAttachmentRequest.pb( + attachment.UploadAttachmentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = attachment.UploadAttachmentResponse.to_json( + attachment.UploadAttachmentResponse() + ) + + request = attachment.UploadAttachmentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = attachment.UploadAttachmentResponse() + + client.upload_attachment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_upload_attachment_rest_bad_request( + transport: str = "rest", request_type=attachment.UploadAttachmentRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.upload_attachment(request) + + +def test_upload_attachment_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + space.ListSpacesRequest, + dict, + ], +) +def test_list_spaces_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = space.ListSpacesResponse( + next_page_token="next_page_token_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 = space.ListSpacesResponse.pb(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_spaces(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSpacesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_spaces_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_list_spaces" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_list_spaces" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = space.ListSpacesRequest.pb(space.ListSpacesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = space.ListSpacesResponse.to_json( + space.ListSpacesResponse() + ) + + request = space.ListSpacesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = space.ListSpacesResponse() + + client.list_spaces( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_spaces_rest_bad_request( + transport: str = "rest", request_type=space.ListSpacesRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_spaces(request) + + +def test_list_spaces_rest_pager(transport: str = "rest"): + client = ChatServiceClient( + 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 = ( + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + space.Space(), + ], + next_page_token="abc", + ), + space.ListSpacesResponse( + spaces=[], + next_page_token="def", + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + ], + next_page_token="ghi", + ), + space.ListSpacesResponse( + spaces=[ + space.Space(), + space.Space(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(space.ListSpacesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {} + + pager = client.list_spaces(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, space.Space) for i in results) + + pages = list(client.list_spaces(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + space.GetSpaceRequest, + dict, + ], +) +def test_get_space_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = space.Space( + name="name_value", + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = space.Space.pb(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_space(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == "name_value" + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_get_space_rest_required_fields(request_type=space.GetSpaceRequest): + transport_class = transports.ChatServiceRestTransport + + 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_space._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_space._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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = space.Space() + # 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 = space.Space.pb(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_space(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_space_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_space_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_get_space" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_get_space" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = space.GetSpaceRequest.pb(space.GetSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = space.Space.to_json(space.Space()) + + request = space.GetSpaceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = space.Space() + + client.get_space( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_space_rest_bad_request( + transport: str = "rest", request_type=space.GetSpaceRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_space(request) + + +def test_get_space_rest_flattened(): + client = ChatServiceClient( + 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 = space.Space() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1"} + + # 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 = space.Space.pb(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_space(**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=spaces/*}" % client.transport._host, args[1] + ) + + +def test_get_space_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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_space( + space.GetSpaceRequest(), + name="name_value", + ) + + +def test_get_space_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_space.CreateSpaceRequest, + dict, + ], +) +def test_create_space_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["space"] = { + "name": "name_value", + "type_": 1, + "space_type": 1, + "single_user_bot_dm": True, + "threaded": True, + "display_name": "display_name_value", + "external_user_allowed": True, + "space_threading_state": 2, + "space_details": { + "description": "description_value", + "guidelines": "guidelines_value", + }, + "space_history_state": 1, + "import_mode": True, + "create_time": {"seconds": 751, "nanos": 543}, + "admin_installed": 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 = gc_space.CreateSpaceRequest.meta.fields["space"] + + 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["space"].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["space"][field])): + del request_init["space"][field][i][subfield] + else: + del request_init["space"][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 = gc_space.Space( + name="name_value", + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_space.Space.pb(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.create_space(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_space.Space) + assert response.name == "name_value" + assert response.type_ == gc_space.Space.Type.ROOM + assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_create_space_rest_required_fields(request_type=gc_space.CreateSpaceRequest): + transport_class = transports.ChatServiceRestTransport + + 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() + ).create_space._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() + ).create_space._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gc_space.Space() + # 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 = gc_space.Space.pb(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.create_space(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_space_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("space",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_space_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_create_space" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_create_space" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gc_space.CreateSpaceRequest.pb(gc_space.CreateSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gc_space.Space.to_json(gc_space.Space()) + + request = gc_space.CreateSpaceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gc_space.Space() + + client.create_space( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_space_rest_bad_request( + transport: str = "rest", request_type=gc_space.CreateSpaceRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_space(request) + + +def test_create_space_rest_flattened(): + client = ChatServiceClient( + 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 = gc_space.Space() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + space=gc_space.Space(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 = gc_space.Space.pb(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.create_space(**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/spaces" % client.transport._host, args[1]) + + +def test_create_space_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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_space( + gc_space.CreateSpaceRequest(), + space=gc_space.Space(name="name_value"), + ) + + +def test_create_space_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + space_setup.SetUpSpaceRequest, + dict, + ], +) +def test_set_up_space_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = space.Space( + name="name_value", + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = space.Space.pb(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.set_up_space(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == "name_value" + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_set_up_space_rest_required_fields(request_type=space_setup.SetUpSpaceRequest): + transport_class = transports.ChatServiceRestTransport + + 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() + ).set_up_space._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() + ).set_up_space._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = space.Space() + # 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 = space.Space.pb(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.set_up_space(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_up_space_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_up_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("space",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_up_space_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_set_up_space" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_set_up_space" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = space_setup.SetUpSpaceRequest.pb(space_setup.SetUpSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = space.Space.to_json(space.Space()) + + request = space_setup.SetUpSpaceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = space.Space() + + client.set_up_space( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_up_space_rest_bad_request( + transport: str = "rest", request_type=space_setup.SetUpSpaceRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_up_space(request) + + +def test_set_up_space_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_space.UpdateSpaceRequest, + dict, + ], +) +def test_update_space_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"space": {"name": "spaces/sample1"}} + request_init["space"] = { + "name": "spaces/sample1", + "type_": 1, + "space_type": 1, + "single_user_bot_dm": True, + "threaded": True, + "display_name": "display_name_value", + "external_user_allowed": True, + "space_threading_state": 2, + "space_details": { + "description": "description_value", + "guidelines": "guidelines_value", + }, + "space_history_state": 1, + "import_mode": True, + "create_time": {"seconds": 751, "nanos": 543}, + "admin_installed": 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 = gc_space.UpdateSpaceRequest.meta.fields["space"] + + 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["space"].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["space"][field])): + del request_init["space"][field][i][subfield] + else: + del request_init["space"][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 = gc_space.Space( + name="name_value", + type_=gc_space.Space.Type.ROOM, + space_type=gc_space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=gc_space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_space.Space.pb(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_space(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_space.Space) + assert response.name == "name_value" + assert response.type_ == gc_space.Space.Type.ROOM + assert response.space_type == gc_space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == gc_space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_update_space_rest_required_fields(request_type=gc_space.UpdateSpaceRequest): + transport_class = transports.ChatServiceRestTransport + + 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_space._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_space._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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gc_space.Space() + # 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 = gc_space.Space.pb(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_space(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_space_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("space",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_space_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_update_space" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_update_space" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gc_space.UpdateSpaceRequest.pb(gc_space.UpdateSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gc_space.Space.to_json(gc_space.Space()) + + request = gc_space.UpdateSpaceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gc_space.Space() + + client.update_space( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_space_rest_bad_request( + transport: str = "rest", request_type=gc_space.UpdateSpaceRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"space": {"name": "spaces/sample1"}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_space(request) + + +def test_update_space_rest_flattened(): + client = ChatServiceClient( + 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 = gc_space.Space() + + # get arguments that satisfy an http rule for this method + sample_request = {"space": {"name": "spaces/sample1"}} + + # get truthy value for each flattened field + mock_args = dict( + space=gc_space.Space(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 = gc_space.Space.pb(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_space(**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/{space.name=spaces/*}" % client.transport._host, args[1] + ) + + +def test_update_space_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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_space( + gc_space.UpdateSpaceRequest(), + space=gc_space.Space(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_space_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + space.DeleteSpaceRequest, + dict, + ], +) +def test_delete_space_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_space(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_space_rest_required_fields(request_type=space.DeleteSpaceRequest): + transport_class = transports.ChatServiceRestTransport + + 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_space._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_space._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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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 = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_space(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_space_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_space_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "pre_delete_space" + ) as pre: + pre.assert_not_called() + pb_message = space.DeleteSpaceRequest.pb(space.DeleteSpaceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = space.DeleteSpaceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_space( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_space_rest_bad_request( + transport: str = "rest", request_type=space.DeleteSpaceRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_space(request) + + +def test_delete_space_rest_flattened(): + client = ChatServiceClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1"} + + # 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 = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_space(**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=spaces/*}" % client.transport._host, args[1] + ) + + +def test_delete_space_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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_space( + space.DeleteSpaceRequest(), + name="name_value", + ) + + +def test_delete_space_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + space.CompleteImportSpaceRequest, + dict, + ], +) +def test_complete_import_space_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = space.CompleteImportSpaceResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = space.CompleteImportSpaceResponse.pb(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_import_space(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, space.CompleteImportSpaceResponse) + + +def test_complete_import_space_rest_required_fields( + request_type=space.CompleteImportSpaceRequest, +): + transport_class = transports.ChatServiceRestTransport + + 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() + ).complete_import_space._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() + ).complete_import_space._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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = space.CompleteImportSpaceResponse() + # 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 = space.CompleteImportSpaceResponse.pb(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_import_space(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_complete_import_space_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.complete_import_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_complete_import_space_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_complete_import_space" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_complete_import_space" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = space.CompleteImportSpaceRequest.pb( + space.CompleteImportSpaceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = space.CompleteImportSpaceResponse.to_json( + space.CompleteImportSpaceResponse() + ) + + request = space.CompleteImportSpaceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = space.CompleteImportSpaceResponse() + + client.complete_import_space( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_complete_import_space_rest_bad_request( + transport: str = "rest", request_type=space.CompleteImportSpaceRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.complete_import_space(request) + + +def test_complete_import_space_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + space.FindDirectMessageRequest, + dict, + ], +) +def test_find_direct_message_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = space.Space( + name="name_value", + type_=space.Space.Type.ROOM, + space_type=space.Space.SpaceType.SPACE, + single_user_bot_dm=True, + threaded=True, + display_name="display_name_value", + external_user_allowed=True, + space_threading_state=space.Space.SpaceThreadingState.THREADED_MESSAGES, + space_history_state=history_state.HistoryState.HISTORY_OFF, + import_mode=True, + admin_installed=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = space.Space.pb(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.find_direct_message(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, space.Space) + assert response.name == "name_value" + assert response.type_ == space.Space.Type.ROOM + assert response.space_type == space.Space.SpaceType.SPACE + assert response.single_user_bot_dm is True + assert response.threaded is True + assert response.display_name == "display_name_value" + assert response.external_user_allowed is True + assert ( + response.space_threading_state + == space.Space.SpaceThreadingState.THREADED_MESSAGES + ) + assert response.space_history_state == history_state.HistoryState.HISTORY_OFF + assert response.import_mode is True + assert response.admin_installed is True + + +def test_find_direct_message_rest_required_fields( + request_type=space.FindDirectMessageRequest, +): + transport_class = transports.ChatServiceRestTransport + + 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 + assert "name" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).find_direct_message._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "name" in jsonified_request + assert jsonified_request["name"] == request_init["name"] + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).find_direct_message._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("name",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = space.Space() + # 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 = space.Space.pb(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.find_direct_message(request) + + expected_params = [ + ( + "name", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_find_direct_message_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.find_direct_message._get_unset_required_fields({}) + assert set(unset_fields) == (set(("name",)) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_find_direct_message_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_find_direct_message" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_find_direct_message" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = space.FindDirectMessageRequest.pb(space.FindDirectMessageRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = space.Space.to_json(space.Space()) + + request = space.FindDirectMessageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = space.Space() + + client.find_direct_message( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_find_direct_message_rest_bad_request( + transport: str = "rest", request_type=space.FindDirectMessageRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.find_direct_message(request) + + +def test_find_direct_message_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_membership.CreateMembershipRequest, + dict, + ], +) +def test_create_membership_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request_init["membership"] = { + "name": "name_value", + "state": 1, + "role": 1, + "member": { + "name": "name_value", + "display_name": "display_name_value", + "domain_id": "domain_id_value", + "type_": 1, + "is_anonymous": True, + }, + "group_member": {"name": "name_value"}, + "create_time": {"seconds": 751, "nanos": 543}, + "delete_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 + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gc_membership.CreateMembershipRequest.meta.fields["membership"] + + 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["membership"].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["membership"][field])): + del request_init["membership"][field][i][subfield] + else: + del request_init["membership"][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 = gc_membership.Membership( + name="name_value", + state=gc_membership.Membership.MembershipState.JOINED, + role=gc_membership.Membership.MembershipRole.ROLE_MEMBER, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gc_membership.Membership.pb(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.create_membership(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_membership.Membership) + assert response.name == "name_value" + assert response.state == gc_membership.Membership.MembershipState.JOINED + assert response.role == gc_membership.Membership.MembershipRole.ROLE_MEMBER + + +def test_create_membership_rest_required_fields( + request_type=gc_membership.CreateMembershipRequest, +): + transport_class = transports.ChatServiceRestTransport + + 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() + ).create_membership._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() + ).create_membership._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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gc_membership.Membership() + # 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 = gc_membership.Membership.pb(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.create_membership(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_membership_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_membership._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "membership", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_membership_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_create_membership" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_create_membership" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gc_membership.CreateMembershipRequest.pb( + gc_membership.CreateMembershipRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gc_membership.Membership.to_json( + gc_membership.Membership() + ) + + request = gc_membership.CreateMembershipRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gc_membership.Membership() + + client.create_membership( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_membership_rest_bad_request( + transport: str = "rest", request_type=gc_membership.CreateMembershipRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_membership(request) + + +def test_create_membership_rest_flattened(): + client = ChatServiceClient( + 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 = gc_membership.Membership() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "spaces/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + membership=gc_membership.Membership(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 = gc_membership.Membership.pb(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.create_membership(**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=spaces/*}/members" % client.transport._host, args[1] + ) + + +def test_create_membership_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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_membership( + gc_membership.CreateMembershipRequest(), + parent="parent_value", + membership=gc_membership.Membership(name="name_value"), + ) + + +def test_create_membership_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + membership.DeleteMembershipRequest, + dict, + ], +) +def test_delete_membership_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/members/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 = membership.Membership( + name="name_value", + state=membership.Membership.MembershipState.JOINED, + role=membership.Membership.MembershipRole.ROLE_MEMBER, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.Membership.pb(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.delete_membership(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == "name_value" + assert response.state == membership.Membership.MembershipState.JOINED + assert response.role == membership.Membership.MembershipRole.ROLE_MEMBER + + +def test_delete_membership_rest_required_fields( + request_type=membership.DeleteMembershipRequest, +): + transport_class = transports.ChatServiceRestTransport + + 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_membership._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_membership._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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.Membership() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = membership.Membership.pb(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.delete_membership(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_membership_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_membership_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_delete_membership" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_delete_membership" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = membership.DeleteMembershipRequest.pb( + membership.DeleteMembershipRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = membership.Membership.to_json( + membership.Membership() + ) + + request = membership.DeleteMembershipRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.Membership() + + client.delete_membership( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_membership_rest_bad_request( + transport: str = "rest", request_type=membership.DeleteMembershipRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/members/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_membership(request) + + +def test_delete_membership_rest_flattened(): + client = ChatServiceClient( + 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 = membership.Membership() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1/members/sample2"} + + # 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 = membership.Membership.pb(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.delete_membership(**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=spaces/*/members/*}" % client.transport._host, args[1] + ) + + +def test_delete_membership_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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_membership( + membership.DeleteMembershipRequest(), + name="name_value", + ) + + +def test_delete_membership_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gc_reaction.CreateReactionRequest, + dict, + ], +) +def test_create_reaction_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1/messages/sample2"} + request_init["reaction"] = { + "name": "name_value", + "user": { + "name": "name_value", + "display_name": "display_name_value", + "domain_id": "domain_id_value", + "type_": 1, + "is_anonymous": True, + }, + "emoji": {"unicode": "unicode_value", "custom_emoji": {"uid": "uid_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 = gc_reaction.CreateReactionRequest.meta.fields["reaction"] + + 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["reaction"].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["reaction"][field])): + del request_init["reaction"][field][i][subfield] + else: + del request_init["reaction"][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 = gc_reaction.Reaction( + 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 = gc_reaction.Reaction.pb(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.create_reaction(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gc_reaction.Reaction) + assert response.name == "name_value" + + +def test_create_reaction_rest_required_fields( + request_type=gc_reaction.CreateReactionRequest, +): + transport_class = transports.ChatServiceRestTransport + + 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() + ).create_reaction._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() + ).create_reaction._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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gc_reaction.Reaction() + # 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 = gc_reaction.Reaction.pb(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.create_reaction(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_reaction_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_reaction._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "reaction", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_reaction_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_create_reaction" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_create_reaction" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gc_reaction.CreateReactionRequest.pb( + gc_reaction.CreateReactionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gc_reaction.Reaction.to_json(gc_reaction.Reaction()) + + request = gc_reaction.CreateReactionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gc_reaction.Reaction() + + client.create_reaction( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_reaction_rest_bad_request( + transport: str = "rest", request_type=gc_reaction.CreateReactionRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1/messages/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_reaction(request) + + +def test_create_reaction_rest_flattened(): + client = ChatServiceClient( + 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 = gc_reaction.Reaction() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "spaces/sample1/messages/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + reaction=gc_reaction.Reaction(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 = gc_reaction.Reaction.pb(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.create_reaction(**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=spaces/*/messages/*}/reactions" % client.transport._host, + args[1], + ) + + +def test_create_reaction_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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_reaction( + gc_reaction.CreateReactionRequest(), + parent="parent_value", + reaction=gc_reaction.Reaction(name="name_value"), + ) + + +def test_create_reaction_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reaction.ListReactionsRequest, + dict, + ], +) +def test_list_reactions_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1/messages/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 = reaction.ListReactionsResponse( + next_page_token="next_page_token_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 = reaction.ListReactionsResponse.pb(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_reactions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReactionsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_reactions_rest_required_fields( + request_type=reaction.ListReactionsRequest, +): + transport_class = transports.ChatServiceRestTransport + + 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_reactions._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_reactions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reaction.ListReactionsResponse() + # 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 = reaction.ListReactionsResponse.pb(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_reactions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_reactions_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_reactions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_reactions_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "post_list_reactions" + ) as post, mock.patch.object( + transports.ChatServiceRestInterceptor, "pre_list_reactions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reaction.ListReactionsRequest.pb(reaction.ListReactionsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = reaction.ListReactionsResponse.to_json( + reaction.ListReactionsResponse() + ) + + request = reaction.ListReactionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reaction.ListReactionsResponse() + + client.list_reactions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_reactions_rest_bad_request( + transport: str = "rest", request_type=reaction.ListReactionsRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "spaces/sample1/messages/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_reactions(request) + + +def test_list_reactions_rest_flattened(): + client = ChatServiceClient( + 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 = reaction.ListReactionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "spaces/sample1/messages/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 = reaction.ListReactionsResponse.pb(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_reactions(**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=spaces/*/messages/*}/reactions" % client.transport._host, + args[1], + ) + + +def test_list_reactions_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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_reactions( + reaction.ListReactionsRequest(), + parent="parent_value", + ) + + +def test_list_reactions_rest_pager(transport: str = "rest"): + client = ChatServiceClient( + 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 = ( + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + reaction.Reaction(), + ], + next_page_token="abc", + ), + reaction.ListReactionsResponse( + reactions=[], + next_page_token="def", + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + ], + next_page_token="ghi", + ), + reaction.ListReactionsResponse( + reactions=[ + reaction.Reaction(), + reaction.Reaction(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(reaction.ListReactionsResponse.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": "spaces/sample1/messages/sample2"} + + pager = client.list_reactions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, reaction.Reaction) for i in results) + + pages = list(client.list_reactions(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + reaction.DeleteReactionRequest, + dict, + ], +) +def test_delete_reaction_rest(request_type): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/messages/sample2/reactions/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_reaction(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_reaction_rest_required_fields( + request_type=reaction.DeleteReactionRequest, +): + transport_class = transports.ChatServiceRestTransport + + 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_reaction._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_reaction._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 = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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 = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_reaction(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_reaction_rest_unset_required_fields(): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_reaction._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_reaction_rest_interceptors(null_interceptor): + transport = transports.ChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ChatServiceRestInterceptor(), + ) + client = ChatServiceClient(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.ChatServiceRestInterceptor, "pre_delete_reaction" + ) as pre: + pre.assert_not_called() + pb_message = reaction.DeleteReactionRequest.pb(reaction.DeleteReactionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = reaction.DeleteReactionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_reaction( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_reaction_rest_bad_request( + transport: str = "rest", request_type=reaction.DeleteReactionRequest +): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "spaces/sample1/messages/sample2/reactions/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_reaction(request) + + +def test_delete_reaction_rest_flattened(): + client = ChatServiceClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "spaces/sample1/messages/sample2/reactions/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 = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_reaction(**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=spaces/*/messages/*/reactions/*}" % client.transport._host, + args[1], + ) + + +def test_delete_reaction_rest_flattened_error(transport: str = "rest"): + client = ChatServiceClient( + 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_reaction( + reaction.DeleteReactionRequest(), + name="name_value", + ) + + +def test_delete_reaction_rest_error(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChatServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ChatServiceClient( + 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 = ChatServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ChatServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ChatServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ChatServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ChatServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ChatServiceGrpcTransport, + transports.ChatServiceGrpcAsyncIOTransport, + transports.ChatServiceRestTransport, + ], +) +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() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = ChatServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ChatServiceGrpcTransport, + ) + + +def test_chat_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ChatServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_chat_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.apps.chat_v1.services.chat_service.transports.ChatServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ChatServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_message", + "list_messages", + "list_memberships", + "get_membership", + "get_message", + "update_message", + "delete_message", + "get_attachment", + "upload_attachment", + "list_spaces", + "get_space", + "create_space", + "set_up_space", + "update_space", + "delete_space", + "complete_import_space", + "find_direct_message", + "create_membership", + "delete_membership", + "create_reaction", + "list_reactions", + "delete_reaction", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_chat_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.apps.chat_v1.services.chat_service.transports.ChatServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ChatServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/chat.bot", + "https://www.googleapis.com/auth/chat.delete", + "https://www.googleapis.com/auth/chat.import", + "https://www.googleapis.com/auth/chat.memberships", + "https://www.googleapis.com/auth/chat.memberships.app", + "https://www.googleapis.com/auth/chat.memberships.readonly", + "https://www.googleapis.com/auth/chat.messages", + "https://www.googleapis.com/auth/chat.messages.create", + "https://www.googleapis.com/auth/chat.messages.reactions", + "https://www.googleapis.com/auth/chat.messages.reactions.create", + "https://www.googleapis.com/auth/chat.messages.reactions.readonly", + "https://www.googleapis.com/auth/chat.messages.readonly", + "https://www.googleapis.com/auth/chat.spaces", + "https://www.googleapis.com/auth/chat.spaces.create", + "https://www.googleapis.com/auth/chat.spaces.readonly", + ), + quota_project_id="octopus", + ) + + +def test_chat_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.apps.chat_v1.services.chat_service.transports.ChatServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ChatServiceTransport() + adc.assert_called_once() + + +def test_chat_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ChatServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/chat.bot", + "https://www.googleapis.com/auth/chat.delete", + "https://www.googleapis.com/auth/chat.import", + "https://www.googleapis.com/auth/chat.memberships", + "https://www.googleapis.com/auth/chat.memberships.app", + "https://www.googleapis.com/auth/chat.memberships.readonly", + "https://www.googleapis.com/auth/chat.messages", + "https://www.googleapis.com/auth/chat.messages.create", + "https://www.googleapis.com/auth/chat.messages.reactions", + "https://www.googleapis.com/auth/chat.messages.reactions.create", + "https://www.googleapis.com/auth/chat.messages.reactions.readonly", + "https://www.googleapis.com/auth/chat.messages.readonly", + "https://www.googleapis.com/auth/chat.spaces", + "https://www.googleapis.com/auth/chat.spaces.create", + "https://www.googleapis.com/auth/chat.spaces.readonly", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ChatServiceGrpcTransport, + transports.ChatServiceGrpcAsyncIOTransport, + ], +) +def test_chat_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/chat.bot", + "https://www.googleapis.com/auth/chat.delete", + "https://www.googleapis.com/auth/chat.import", + "https://www.googleapis.com/auth/chat.memberships", + "https://www.googleapis.com/auth/chat.memberships.app", + "https://www.googleapis.com/auth/chat.memberships.readonly", + "https://www.googleapis.com/auth/chat.messages", + "https://www.googleapis.com/auth/chat.messages.create", + "https://www.googleapis.com/auth/chat.messages.reactions", + "https://www.googleapis.com/auth/chat.messages.reactions.create", + "https://www.googleapis.com/auth/chat.messages.reactions.readonly", + "https://www.googleapis.com/auth/chat.messages.readonly", + "https://www.googleapis.com/auth/chat.spaces", + "https://www.googleapis.com/auth/chat.spaces.create", + "https://www.googleapis.com/auth/chat.spaces.readonly", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ChatServiceGrpcTransport, + transports.ChatServiceGrpcAsyncIOTransport, + transports.ChatServiceRestTransport, + ], +) +def test_chat_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ChatServiceGrpcTransport, grpc_helpers), + (transports.ChatServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_chat_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "chat.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/chat.bot", + "https://www.googleapis.com/auth/chat.delete", + "https://www.googleapis.com/auth/chat.import", + "https://www.googleapis.com/auth/chat.memberships", + "https://www.googleapis.com/auth/chat.memberships.app", + "https://www.googleapis.com/auth/chat.memberships.readonly", + "https://www.googleapis.com/auth/chat.messages", + "https://www.googleapis.com/auth/chat.messages.create", + "https://www.googleapis.com/auth/chat.messages.reactions", + "https://www.googleapis.com/auth/chat.messages.reactions.create", + "https://www.googleapis.com/auth/chat.messages.reactions.readonly", + "https://www.googleapis.com/auth/chat.messages.readonly", + "https://www.googleapis.com/auth/chat.spaces", + "https://www.googleapis.com/auth/chat.spaces.create", + "https://www.googleapis.com/auth/chat.spaces.readonly", + ), + scopes=["1", "2"], + default_host="chat.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.ChatServiceGrpcTransport, transports.ChatServiceGrpcAsyncIOTransport], +) +def test_chat_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_chat_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.ChatServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_chat_service_host_no_port(transport_name): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint="chat.googleapis.com"), + transport=transport_name, + ) + assert client.transport._host == ( + "chat.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://chat.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_chat_service_host_with_port(transport_name): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="chat.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "chat.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://chat.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_chat_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ChatServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ChatServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_message._session + session2 = client2.transport.create_message._session + assert session1 != session2 + session1 = client1.transport.list_messages._session + session2 = client2.transport.list_messages._session + assert session1 != session2 + session1 = client1.transport.list_memberships._session + session2 = client2.transport.list_memberships._session + assert session1 != session2 + session1 = client1.transport.get_membership._session + session2 = client2.transport.get_membership._session + assert session1 != session2 + session1 = client1.transport.get_message._session + session2 = client2.transport.get_message._session + assert session1 != session2 + session1 = client1.transport.update_message._session + session2 = client2.transport.update_message._session + assert session1 != session2 + session1 = client1.transport.delete_message._session + session2 = client2.transport.delete_message._session + assert session1 != session2 + session1 = client1.transport.get_attachment._session + session2 = client2.transport.get_attachment._session + assert session1 != session2 + session1 = client1.transport.upload_attachment._session + session2 = client2.transport.upload_attachment._session + assert session1 != session2 + session1 = client1.transport.list_spaces._session + session2 = client2.transport.list_spaces._session + assert session1 != session2 + session1 = client1.transport.get_space._session + session2 = client2.transport.get_space._session + assert session1 != session2 + session1 = client1.transport.create_space._session + session2 = client2.transport.create_space._session + assert session1 != session2 + session1 = client1.transport.set_up_space._session + session2 = client2.transport.set_up_space._session + assert session1 != session2 + session1 = client1.transport.update_space._session + session2 = client2.transport.update_space._session + assert session1 != session2 + session1 = client1.transport.delete_space._session + session2 = client2.transport.delete_space._session + assert session1 != session2 + session1 = client1.transport.complete_import_space._session + session2 = client2.transport.complete_import_space._session + assert session1 != session2 + session1 = client1.transport.find_direct_message._session + session2 = client2.transport.find_direct_message._session + assert session1 != session2 + session1 = client1.transport.create_membership._session + session2 = client2.transport.create_membership._session + assert session1 != session2 + session1 = client1.transport.delete_membership._session + session2 = client2.transport.delete_membership._session + assert session1 != session2 + session1 = client1.transport.create_reaction._session + session2 = client2.transport.create_reaction._session + assert session1 != session2 + session1 = client1.transport.list_reactions._session + session2 = client2.transport.list_reactions._session + assert session1 != session2 + session1 = client1.transport.delete_reaction._session + session2 = client2.transport.delete_reaction._session + assert session1 != session2 + + +def test_chat_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ChatServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_chat_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ChatServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.ChatServiceGrpcTransport, transports.ChatServiceGrpcAsyncIOTransport], +) +def test_chat_service_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.ChatServiceGrpcTransport, transports.ChatServiceGrpcAsyncIOTransport], +) +def test_chat_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_attachment_path(): + space = "squid" + message = "clam" + attachment = "whelk" + expected = "spaces/{space}/messages/{message}/attachments/{attachment}".format( + space=space, + message=message, + attachment=attachment, + ) + actual = ChatServiceClient.attachment_path(space, message, attachment) + assert expected == actual + + +def test_parse_attachment_path(): + expected = { + "space": "octopus", + "message": "oyster", + "attachment": "nudibranch", + } + path = ChatServiceClient.attachment_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_attachment_path(path) + assert expected == actual + + +def test_membership_path(): + space = "cuttlefish" + member = "mussel" + expected = "spaces/{space}/members/{member}".format( + space=space, + member=member, + ) + actual = ChatServiceClient.membership_path(space, member) + assert expected == actual + + +def test_parse_membership_path(): + expected = { + "space": "winkle", + "member": "nautilus", + } + path = ChatServiceClient.membership_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_membership_path(path) + assert expected == actual + + +def test_message_path(): + space = "scallop" + message = "abalone" + expected = "spaces/{space}/messages/{message}".format( + space=space, + message=message, + ) + actual = ChatServiceClient.message_path(space, message) + assert expected == actual + + +def test_parse_message_path(): + expected = { + "space": "squid", + "message": "clam", + } + path = ChatServiceClient.message_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_message_path(path) + assert expected == actual + + +def test_quoted_message_metadata_path(): + space = "whelk" + message = "octopus" + quoted_message_metadata = "oyster" + expected = "spaces/{space}/messages/{message}/quotedMessageMetadata/{quoted_message_metadata}".format( + space=space, + message=message, + quoted_message_metadata=quoted_message_metadata, + ) + actual = ChatServiceClient.quoted_message_metadata_path( + space, message, quoted_message_metadata + ) + assert expected == actual + + +def test_parse_quoted_message_metadata_path(): + expected = { + "space": "nudibranch", + "message": "cuttlefish", + "quoted_message_metadata": "mussel", + } + path = ChatServiceClient.quoted_message_metadata_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_quoted_message_metadata_path(path) + assert expected == actual + + +def test_reaction_path(): + space = "winkle" + message = "nautilus" + reaction = "scallop" + expected = "spaces/{space}/messages/{message}/reactions/{reaction}".format( + space=space, + message=message, + reaction=reaction, + ) + actual = ChatServiceClient.reaction_path(space, message, reaction) + assert expected == actual + + +def test_parse_reaction_path(): + expected = { + "space": "abalone", + "message": "squid", + "reaction": "clam", + } + path = ChatServiceClient.reaction_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_reaction_path(path) + assert expected == actual + + +def test_space_path(): + space = "whelk" + expected = "spaces/{space}".format( + space=space, + ) + actual = ChatServiceClient.space_path(space) + assert expected == actual + + +def test_parse_space_path(): + expected = { + "space": "octopus", + } + path = ChatServiceClient.space_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_space_path(path) + assert expected == actual + + +def test_thread_path(): + space = "oyster" + thread = "nudibranch" + expected = "spaces/{space}/threads/{thread}".format( + space=space, + thread=thread, + ) + actual = ChatServiceClient.thread_path(space, thread) + assert expected == actual + + +def test_parse_thread_path(): + expected = { + "space": "cuttlefish", + "thread": "mussel", + } + path = ChatServiceClient.thread_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_thread_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ChatServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = ChatServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ChatServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = ChatServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = ChatServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = ChatServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format( + project=project, + ) + actual = ChatServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = ChatServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = ChatServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = ChatServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ChatServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.ChatServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ChatServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ChatServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ChatServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = ChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (ChatServiceClient, transports.ChatServiceGrpcTransport), + (ChatServiceAsyncClient, transports.ChatServiceGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-apps-meet/CHANGELOG.md b/packages/google-apps-meet/CHANGELOG.md index 858035abf2a0..13a01c52f09f 100644 --- a/packages/google-apps-meet/CHANGELOG.md +++ b/packages/google-apps-meet/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.6](https://github.com/googleapis/google-cloud-python/compare/google-apps-meet-v0.1.5...google-apps-meet-v0.1.6) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [0.1.5](https://github.com/googleapis/google-cloud-python/compare/google-apps-meet-v0.1.4...google-apps-meet-v0.1.5) (2024-02-22) 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 ae12f4dfd596..60402a4567d1 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.5" # {x-release-please-version} +__version__ = "0.1.6" # {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 ae12f4dfd596..60402a4567d1 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.5" # {x-release-please-version} +__version__ = "0.1.6" # {x-release-please-version} 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 ae12f4dfd596..60402a4567d1 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.5" # {x-release-please-version} +__version__ = "0.1.6" # {x-release-please-version} 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 dd7268a3738c..03e7d6d6557a 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.5" + "version": "0.1.6" }, "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 8ce33e704e87..a5bd7234fadb 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.5" + "version": "0.1.6" }, "snippets": [ { diff --git a/packages/google-apps-meet/setup.py b/packages/google-apps-meet/setup.py index 3083d6d5339a..63296f790fdb 100644 --- a/packages/google-apps-meet/setup.py +++ b/packages/google-apps-meet/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-apps-script-type/CHANGELOG.md b/packages/google-apps-script-type/CHANGELOG.md index 8013df3b4f0d..391095a5ceca 100644 --- a/packages/google-apps-script-type/CHANGELOG.md +++ b/packages/google-apps-script-type/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.3.8](https://github.com/googleapis/google-cloud-python/compare/google-apps-script-type-v0.3.7...google-apps-script-type-v0.3.8) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [0.3.7](https://github.com/googleapis/google-cloud-python/compare/google-apps-script-type-v0.3.6...google-apps-script-type-v0.3.7) (2024-02-22) diff --git a/packages/google-apps-script-type/google/apps/script/type/calendar/gapic_version.py b/packages/google-apps-script-type/google/apps/script/type/calendar/gapic_version.py index 91090a840535..9c72996dc3e9 100644 --- a/packages/google-apps-script-type/google/apps/script/type/calendar/gapic_version.py +++ b/packages/google-apps-script-type/google/apps/script/type/calendar/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.7" # {x-release-please-version} +__version__ = "0.3.8" # {x-release-please-version} diff --git a/packages/google-apps-script-type/google/apps/script/type/docs/gapic_version.py b/packages/google-apps-script-type/google/apps/script/type/docs/gapic_version.py index 91090a840535..9c72996dc3e9 100644 --- a/packages/google-apps-script-type/google/apps/script/type/docs/gapic_version.py +++ b/packages/google-apps-script-type/google/apps/script/type/docs/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.7" # {x-release-please-version} +__version__ = "0.3.8" # {x-release-please-version} diff --git a/packages/google-apps-script-type/google/apps/script/type/drive/gapic_version.py b/packages/google-apps-script-type/google/apps/script/type/drive/gapic_version.py index 91090a840535..9c72996dc3e9 100644 --- a/packages/google-apps-script-type/google/apps/script/type/drive/gapic_version.py +++ b/packages/google-apps-script-type/google/apps/script/type/drive/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.7" # {x-release-please-version} +__version__ = "0.3.8" # {x-release-please-version} diff --git a/packages/google-apps-script-type/google/apps/script/type/gapic_version.py b/packages/google-apps-script-type/google/apps/script/type/gapic_version.py index 91090a840535..9c72996dc3e9 100644 --- a/packages/google-apps-script-type/google/apps/script/type/gapic_version.py +++ b/packages/google-apps-script-type/google/apps/script/type/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.7" # {x-release-please-version} +__version__ = "0.3.8" # {x-release-please-version} diff --git a/packages/google-apps-script-type/google/apps/script/type/gmail/gapic_version.py b/packages/google-apps-script-type/google/apps/script/type/gmail/gapic_version.py index 91090a840535..9c72996dc3e9 100644 --- a/packages/google-apps-script-type/google/apps/script/type/gmail/gapic_version.py +++ b/packages/google-apps-script-type/google/apps/script/type/gmail/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.7" # {x-release-please-version} +__version__ = "0.3.8" # {x-release-please-version} diff --git a/packages/google-apps-script-type/google/apps/script/type/sheets/gapic_version.py b/packages/google-apps-script-type/google/apps/script/type/sheets/gapic_version.py index 91090a840535..9c72996dc3e9 100644 --- a/packages/google-apps-script-type/google/apps/script/type/sheets/gapic_version.py +++ b/packages/google-apps-script-type/google/apps/script/type/sheets/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.7" # {x-release-please-version} +__version__ = "0.3.8" # {x-release-please-version} diff --git a/packages/google-apps-script-type/google/apps/script/type/slides/gapic_version.py b/packages/google-apps-script-type/google/apps/script/type/slides/gapic_version.py index 91090a840535..9c72996dc3e9 100644 --- a/packages/google-apps-script-type/google/apps/script/type/slides/gapic_version.py +++ b/packages/google-apps-script-type/google/apps/script/type/slides/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.7" # {x-release-please-version} +__version__ = "0.3.8" # {x-release-please-version} diff --git a/packages/google-apps-script-type/setup.py b/packages/google-apps-script-type/setup.py index b72fcfc665ca..abcd7c7ae211 100644 --- a/packages/google-apps-script-type/setup.py +++ b/packages/google-apps-script-type/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-area120-tables/CHANGELOG.md b/packages/google-area120-tables/CHANGELOG.md index c61f04101fa8..ba92d587e16a 100644 --- a/packages/google-area120-tables/CHANGELOG.md +++ b/packages/google-area120-tables/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.11.9](https://github.com/googleapis/google-cloud-python/compare/google-area120-tables-v0.11.8...google-area120-tables-v0.11.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [0.11.8](https://github.com/googleapis/google-cloud-python/compare/google-area120-tables-v0.11.7...google-area120-tables-v0.11.8) (2024-02-22) 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 651274e67675..456019f7dbab 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.8" # {x-release-please-version} +__version__ = "0.11.9" # {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 651274e67675..456019f7dbab 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.8" # {x-release-please-version} +__version__ = "0.11.9" # {x-release-please-version} 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 dc504f6bd64f..9d09c68d0b39 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.8" + "version": "0.11.9" }, "snippets": [ { diff --git a/packages/google-area120-tables/setup.py b/packages/google-area120-tables/setup.py index 44b47ae85864..420ce60e8d14 100644 --- a/packages/google-area120-tables/setup.py +++ b/packages/google-area120-tables/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-access-approval/CHANGELOG.md b/packages/google-cloud-access-approval/CHANGELOG.md index 6299db6af90d..87058353d6af 100644 --- a/packages/google-cloud-access-approval/CHANGELOG.md +++ b/packages/google-cloud-access-approval/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.13.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-access-approval-v1.13.2...google-cloud-access-approval-v1.13.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [1.13.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-access-approval-v1.13.1...google-cloud-access-approval-v1.13.2) (2024-02-22) 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 3434b217efee..40e034931fac 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.13.2" # {x-release-please-version} +__version__ = "1.13.3" # {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 3434b217efee..40e034931fac 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.13.2" # {x-release-please-version} +__version__ = "1.13.3" # {x-release-please-version} 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 e60b64dad3a9..e9b6e171a3ab 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.13.2" + "version": "1.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-access-approval/setup.py b/packages/google-cloud-access-approval/setup.py index 53aaba117a72..a64be18ecc85 100644 --- a/packages/google-cloud-access-approval/setup.py +++ b/packages/google-cloud-access-approval/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-advisorynotifications/CHANGELOG.md b/packages/google-cloud-advisorynotifications/CHANGELOG.md index 0b49e1472db4..d478fc4da0d0 100644 --- a/packages/google-cloud-advisorynotifications/CHANGELOG.md +++ b/packages/google-cloud-advisorynotifications/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.3.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-advisorynotifications-v0.3.6...google-cloud-advisorynotifications-v0.3.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [0.3.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-advisorynotifications-v0.3.5...google-cloud-advisorynotifications-v0.3.6) (2024-02-22) 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 dca6dc837e67..91090a840535 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.6" # {x-release-please-version} +__version__ = "0.3.7" # {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 dca6dc837e67..91090a840535 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.6" # {x-release-please-version} +__version__ = "0.3.7" # {x-release-please-version} 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 1abed1fff08d..cdf393afd193 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.6" + "version": "0.3.7" }, "snippets": [ { diff --git a/packages/google-cloud-advisorynotifications/setup.py b/packages/google-cloud-advisorynotifications/setup.py index 6e2556d11990..da84cb3f3527 100644 --- a/packages/google-cloud-advisorynotifications/setup.py +++ b/packages/google-cloud-advisorynotifications/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-alloydb-connectors/CHANGELOG.md b/packages/google-cloud-alloydb-connectors/CHANGELOG.md index 899e33b05ce0..bc5f512e4209 100644 --- a/packages/google-cloud-alloydb-connectors/CHANGELOG.md +++ b/packages/google-cloud-alloydb-connectors/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.4](https://github.com/googleapis/google-cloud-python/compare/google-cloud-alloydb-connectors-v0.1.3...google-cloud-alloydb-connectors-v0.1.4) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [0.1.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-alloydb-connectors-v0.1.2...google-cloud-alloydb-connectors-v0.1.3) (2024-02-22) diff --git a/packages/google-cloud-alloydb-connectors/google/cloud/alloydb/connectors/gapic_version.py b/packages/google-cloud-alloydb-connectors/google/cloud/alloydb/connectors/gapic_version.py index 536d6648a6f0..286ce4ad5531 100644 --- a/packages/google-cloud-alloydb-connectors/google/cloud/alloydb/connectors/gapic_version.py +++ b/packages/google-cloud-alloydb-connectors/google/cloud/alloydb/connectors/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-alloydb-connectors/google/cloud/alloydb/connectors_v1/gapic_version.py b/packages/google-cloud-alloydb-connectors/google/cloud/alloydb/connectors_v1/gapic_version.py index 536d6648a6f0..286ce4ad5531 100644 --- a/packages/google-cloud-alloydb-connectors/google/cloud/alloydb/connectors_v1/gapic_version.py +++ b/packages/google-cloud-alloydb-connectors/google/cloud/alloydb/connectors_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-alloydb-connectors/setup.py b/packages/google-cloud-alloydb-connectors/setup.py index ba04cae074b2..3df625449309 100644 --- a/packages/google-cloud-alloydb-connectors/setup.py +++ b/packages/google-cloud-alloydb-connectors/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-alloydb/CHANGELOG.md b/packages/google-cloud-alloydb/CHANGELOG.md index 3034b35cd98a..3ed4da47d798 100644 --- a/packages/google-cloud-alloydb/CHANGELOG.md +++ b/packages/google-cloud-alloydb/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## [0.3.10](https://github.com/googleapis/google-cloud-python/compare/google-cloud-alloydb-v0.3.9...google-cloud-alloydb-v0.3.10) (2024-03-05) + + +### Features + +* Add new API to list the databases in a project and location ([3f2a93c](https://github.com/googleapis/google-cloud-python/commit/3f2a93c4892bd5995a87c152f2d54e26aa6cf138)) +* Add PSC cluster and instance configuration settings to enable/disable PSC and obtain the PSC endpoint name ([3f2a93c](https://github.com/googleapis/google-cloud-python/commit/3f2a93c4892bd5995a87c152f2d54e26aa6cf138)) +* Add support for getting PSC DNS name from the GetConnectionInfo API ([3f2a93c](https://github.com/googleapis/google-cloud-python/commit/3f2a93c4892bd5995a87c152f2d54e26aa6cf138)) +* Add support for obtaining the public IP address of an Instance ([3f2a93c](https://github.com/googleapis/google-cloud-python/commit/3f2a93c4892bd5995a87c152f2d54e26aa6cf138)) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([3f2a93c](https://github.com/googleapis/google-cloud-python/commit/3f2a93c4892bd5995a87c152f2d54e26aa6cf138)) + + +### Documentation + +* Clarified read pool config is for read pool type instances ([3f2a93c](https://github.com/googleapis/google-cloud-python/commit/3f2a93c4892bd5995a87c152f2d54e26aa6cf138)) + ## [0.3.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-alloydb-v0.3.8...google-cloud-alloydb-v0.3.9) (2024-02-22) 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 807d78fcb4c5..2373370ae5a0 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.9" # {x-release-please-version} +__version__ = "0.3.10" # {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 807d78fcb4c5..2373370ae5a0 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.9" # {x-release-please-version} +__version__ = "0.3.10" # {x-release-please-version} 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 807d78fcb4c5..2373370ae5a0 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.9" # {x-release-please-version} +__version__ = "0.3.10" # {x-release-please-version} diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/types/resources.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/types/resources.py index 6dccd47d271a..8fdbdb0c44ab 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/types/resources.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/types/resources.py @@ -1139,6 +1139,10 @@ class Instance(proto.Message): Output only. The IP address for the Instance. This is the connection endpoint for an end-user application. + public_ip_address (str): + Output only. The public IP addresses for the Instance. This + is available ONLY when enable_public_ip is set. This is the + connection endpoint for an end-user application. reconciling (bool): Output only. Reconciling (https://google.aip.dev/128#reconciliation). Set @@ -1657,6 +1661,10 @@ class AuthorizedNetwork(proto.Message): proto.STRING, number=15, ) + public_ip_address: str = proto.Field( + proto.STRING, + number=27, + ) reconciling: bool = proto.Field( proto.BOOL, number=16, @@ -1725,6 +1733,9 @@ class ConnectionInfo(proto.Message): to RFC 5246. instance_uid (str): Output only. The unique ID of the Instance. + psc_dns_name (str): + Output only. The DNS name to use with PSC for + the Instance. """ name: str = proto.Field( @@ -1747,6 +1758,10 @@ class ConnectionInfo(proto.Message): proto.STRING, number=4, ) + psc_dns_name: str = proto.Field( + proto.STRING, + number=6, + ) class Backup(proto.Message): diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/__init__.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/__init__.py index 44f091c27cfb..48be9b9efcc1 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/__init__.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/__init__.py @@ -29,6 +29,7 @@ ContinuousBackupConfig, ContinuousBackupInfo, ContinuousBackupSource, + Database, DatabaseVersion, EncryptionConfig, EncryptionInfo, @@ -69,6 +70,8 @@ ListBackupsResponse, ListClustersRequest, ListClustersResponse, + ListDatabasesRequest, + ListDatabasesResponse, ListInstancesRequest, ListInstancesResponse, ListSupportedDatabaseFlagsRequest, @@ -108,6 +111,7 @@ "CreateSecondaryClusterRequest", "CreateSecondaryInstanceRequest", "CreateUserRequest", + "Database", "DatabaseVersion", "DeleteBackupRequest", "DeleteClusterRequest", @@ -130,6 +134,8 @@ "ListBackupsResponse", "ListClustersRequest", "ListClustersResponse", + "ListDatabasesRequest", + "ListDatabasesResponse", "ListInstancesRequest", "ListInstancesResponse", "ListSupportedDatabaseFlagsRequest", diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/gapic_metadata.json b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/gapic_metadata.json index 5b0f0bfb7ae0..8fcd1982baa7 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/gapic_metadata.json +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/gapic_metadata.json @@ -115,6 +115,11 @@ "list_clusters" ] }, + "ListDatabases": { + "methods": [ + "list_databases" + ] + }, "ListInstances": { "methods": [ "list_instances" @@ -275,6 +280,11 @@ "list_clusters" ] }, + "ListDatabases": { + "methods": [ + "list_databases" + ] + }, "ListInstances": { "methods": [ "list_instances" @@ -435,6 +445,11 @@ "list_clusters" ] }, + "ListDatabases": { + "methods": [ + "list_databases" + ] + }, "ListInstances": { "methods": [ "list_instances" 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 807d78fcb4c5..2373370ae5a0 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.9" # {x-release-please-version} +__version__ = "0.3.10" # {x-release-please-version} diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/async_client.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/async_client.py index 1aba54f7153d..3178b16e2269 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/async_client.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/async_client.py @@ -84,6 +84,8 @@ class AlloyDBAdminAsyncClient: parse_crypto_key_version_path = staticmethod( AlloyDBAdminClient.parse_crypto_key_version_path ) + database_path = staticmethod(AlloyDBAdminClient.database_path) + parse_database_path = staticmethod(AlloyDBAdminClient.parse_database_path) instance_path = staticmethod(AlloyDBAdminClient.instance_path) parse_instance_path = staticmethod(AlloyDBAdminClient.parse_instance_path) network_path = staticmethod(AlloyDBAdminClient.network_path) @@ -4195,6 +4197,133 @@ async def sample_delete_user(): metadata=metadata, ) + async def list_databases( + self, + request: Optional[Union[service.ListDatabasesRequest, 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.ListDatabasesAsyncPager: + r"""Lists Databases in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + async def sample_list_databases(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListDatabasesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_databases(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1beta.types.ListDatabasesRequest, dict]]): + The request object. Message for requesting list of + Databases. + parent (:class:`str`): + Required. Parent value for + ListDatabasesRequest. + + 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.alloydb_v1beta.services.alloy_db_admin.pagers.ListDatabasesAsyncPager: + Message for response to listing + Databases. + 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." + ) + + request = service.ListDatabasesRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_databases, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListDatabasesAsyncPager( + method=rpc, + request=request, + response=response, + 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-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 6aad8337cb97..bf25f6091c07 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 @@ -284,6 +284,30 @@ def parse_crypto_key_version_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def database_path( + project: str, + location: str, + cluster: str, + database: str, + ) -> str: + """Returns a fully-qualified database string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/databases/{database}".format( + project=project, + location=location, + cluster=cluster, + database=database, + ) + + @staticmethod + def parse_database_path(path: str) -> Dict[str, str]: + """Parses a database path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/databases/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def instance_path( project: str, @@ -4655,6 +4679,124 @@ def sample_delete_user(): metadata=metadata, ) + def list_databases( + self, + request: Optional[Union[service.ListDatabasesRequest, 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.ListDatabasesPager: + r"""Lists Databases in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1beta + + def sample_list_databases(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListDatabasesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_databases(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.alloydb_v1beta.types.ListDatabasesRequest, dict]): + The request object. Message for requesting list of + Databases. + parent (str): + Required. Parent value for + ListDatabasesRequest. + + 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.alloydb_v1beta.services.alloy_db_admin.pagers.ListDatabasesPager: + Message for response to listing + Databases. + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a service.ListDatabasesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListDatabasesRequest): + request = service.ListDatabasesRequest(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_databases] + + # 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.ListDatabasesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "AlloyDBAdminClient": return self diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/pagers.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/pagers.py index b274a03f8c11..7046fbf8d261 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/pagers.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/pagers.py @@ -665,3 +665,131 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDatabasesPager: + """A pager for iterating through ``list_databases`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1beta.types.ListDatabasesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``databases`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDatabases`` requests and continue to iterate + through the ``databases`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1beta.types.ListDatabasesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., service.ListDatabasesResponse], + request: service.ListDatabasesRequest, + response: service.ListDatabasesResponse, + *, + 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.alloydb_v1beta.types.ListDatabasesRequest): + The initial request object. + response (google.cloud.alloydb_v1beta.types.ListDatabasesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = service.ListDatabasesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListDatabasesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.Database]: + for page in self.pages: + yield from page.databases + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDatabasesAsyncPager: + """A pager for iterating through ``list_databases`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1beta.types.ListDatabasesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``databases`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDatabases`` requests and continue to iterate + through the ``databases`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1beta.types.ListDatabasesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[service.ListDatabasesResponse]], + request: service.ListDatabasesRequest, + response: service.ListDatabasesResponse, + *, + 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.alloydb_v1beta.types.ListDatabasesRequest): + The initial request object. + response (google.cloud.alloydb_v1beta.types.ListDatabasesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = service.ListDatabasesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListDatabasesResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[resources.Database]: + async def async_generator(): + async for page in self.pages: + for response in page.databases: + 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-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/base.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/base.py index d69b2034a09d..7cd15f97bb00 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/base.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/base.py @@ -385,6 +385,20 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.list_databases: gapic_v1.method.wrap_method( + self.list_databases, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), } def close(self): @@ -681,6 +695,15 @@ def delete_user( ]: raise NotImplementedError() + @property + def list_databases( + self, + ) -> Callable[ + [service.ListDatabasesRequest], + Union[service.ListDatabasesResponse, Awaitable[service.ListDatabasesResponse]], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/grpc.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/grpc.py index 4cc26d850804..dbf06029766a 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/grpc.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/grpc.py @@ -1084,6 +1084,32 @@ def delete_user(self) -> Callable[[service.DeleteUserRequest], empty_pb2.Empty]: ) return self._stubs["delete_user"] + @property + def list_databases( + self, + ) -> Callable[[service.ListDatabasesRequest], service.ListDatabasesResponse]: + r"""Return a callable for the list databases method over gRPC. + + Lists Databases in a given project and location. + + Returns: + Callable[[~.ListDatabasesRequest], + ~.ListDatabasesResponse]: + 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_databases" not in self._stubs: + self._stubs["list_databases"] = self.grpc_channel.unary_unary( + "/google.cloud.alloydb.v1beta.AlloyDBAdmin/ListDatabases", + request_serializer=service.ListDatabasesRequest.serialize, + response_deserializer=service.ListDatabasesResponse.deserialize, + ) + return self._stubs["list_databases"] + def close(self): self.grpc_channel.close() diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/grpc_asyncio.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/grpc_asyncio.py index 1fb62c3de9d3..2700992e8397 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/grpc_asyncio.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/grpc_asyncio.py @@ -1115,6 +1115,34 @@ def delete_user( ) return self._stubs["delete_user"] + @property + def list_databases( + self, + ) -> Callable[ + [service.ListDatabasesRequest], Awaitable[service.ListDatabasesResponse] + ]: + r"""Return a callable for the list databases method over gRPC. + + Lists Databases in a given project and location. + + Returns: + Callable[[~.ListDatabasesRequest], + Awaitable[~.ListDatabasesResponse]]: + 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_databases" not in self._stubs: + self._stubs["list_databases"] = self.grpc_channel.unary_unary( + "/google.cloud.alloydb.v1beta.AlloyDBAdmin/ListDatabases", + request_serializer=service.ListDatabasesRequest.serialize, + response_deserializer=service.ListDatabasesResponse.deserialize, + ) + return self._stubs["list_databases"] + def close(self): return self.grpc_channel.close() diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/rest.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/rest.py index 463c713f38be..904ae3d67d7a 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/rest.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/transports/rest.py @@ -239,6 +239,14 @@ def post_list_clusters(self, response): logging.log(f"Received response: {response}") return response + def pre_list_databases(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_databases(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_instances(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -761,6 +769,27 @@ def post_list_clusters( """ return response + def pre_list_databases( + self, request: service.ListDatabasesRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.ListDatabasesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_databases + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_list_databases( + self, response: service.ListDatabasesResponse + ) -> service.ListDatabasesResponse: + """Post-rpc interceptor for list_databases + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_list_instances( self, request: service.ListInstancesRequest, metadata: Sequence[Tuple[str, str]] ) -> Tuple[service.ListInstancesRequest, Sequence[Tuple[str, str]]]: @@ -3169,6 +3198,94 @@ def __call__( resp = self._interceptor.post_list_clusters(resp) return resp + class _ListDatabases(AlloyDBAdminRestStub): + def __hash__(self): + return hash("ListDatabases") + + __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 + } + + def __call__( + self, + request: service.ListDatabasesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListDatabasesResponse: + r"""Call the list databases method over HTTP. + + Args: + request (~.service.ListDatabasesRequest): + The request object. Message for requesting list of + Databases. + 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: + ~.service.ListDatabasesResponse: + Message for response to listing + Databases. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/clusters/*}/databases", + }, + ] + request, metadata = self._interceptor.pre_list_databases(request, metadata) + pb_request = service.ListDatabasesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListDatabasesResponse() + pb_resp = service.ListDatabasesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_databases(resp) + return resp + class _ListInstances(AlloyDBAdminRestStub): def __hash__(self): return hash("ListInstances") @@ -4248,6 +4365,14 @@ def list_clusters( # In C++ this would require a dynamic_cast return self._ListClusters(self._session, self._host, self._interceptor) # type: ignore + @property + def list_databases( + self, + ) -> Callable[[service.ListDatabasesRequest], service.ListDatabasesResponse]: + # 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._ListDatabases(self._session, self._host, self._interceptor) # type: ignore + @property def list_instances( self, diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/types/__init__.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/types/__init__.py index 3b24cd81f761..a9314ac6676e 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/types/__init__.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/types/__init__.py @@ -23,6 +23,7 @@ ContinuousBackupConfig, ContinuousBackupInfo, ContinuousBackupSource, + Database, DatabaseVersion, EncryptionConfig, EncryptionInfo, @@ -63,6 +64,8 @@ ListBackupsResponse, ListClustersRequest, ListClustersResponse, + ListDatabasesRequest, + ListDatabasesResponse, ListInstancesRequest, ListInstancesResponse, ListSupportedDatabaseFlagsRequest, @@ -88,6 +91,7 @@ "ContinuousBackupConfig", "ContinuousBackupInfo", "ContinuousBackupSource", + "Database", "EncryptionConfig", "EncryptionInfo", "Instance", @@ -127,6 +131,8 @@ "ListBackupsResponse", "ListClustersRequest", "ListClustersResponse", + "ListDatabasesRequest", + "ListDatabasesResponse", "ListInstancesRequest", "ListInstancesResponse", "ListSupportedDatabaseFlagsRequest", diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/types/resources.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/types/resources.py index 5409a6415ad5..7850e082a134 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/types/resources.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/types/resources.py @@ -46,6 +46,7 @@ "Backup", "SupportedDatabaseFlag", "User", + "Database", }, ) @@ -749,6 +750,8 @@ class Cluster(proto.Message): primary_config (google.cloud.alloydb_v1beta.types.Cluster.PrimaryConfig): Output only. Cross Region replication config specific to PRIMARY cluster. + satisfies_pzs (bool): + Output only. Reserved for future use. """ class State(proto.Enum): @@ -823,7 +826,7 @@ class NetworkConfig(proto.Message): Attributes: network (str): - Required. The resource link for the VPC network in which + Optional. The resource link for the VPC network in which cluster resources are created and from which they are accessible via Private IP. The network must belong to the same project as the cluster. It is specified in the form: @@ -836,8 +839,8 @@ class NetworkConfig(proto.Message): for this cluster will be created in the allocated range. The range name must comply with RFC 1035. Specifically, the name must be 1-63 characters long and match the regular - expression `a-z <[-a-z0-9]*[a-z0-9]>`__?. Field name is - intended to be consistent with CloudSQL. + expression ``[a-z]([-a-z0-9]*[a-z0-9])?``. Field name is + intended to be consistent with Cloud SQL. """ network: str = proto.Field( @@ -1007,6 +1010,10 @@ class PrimaryConfig(proto.Message): number=23, message=PrimaryConfig, ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=30, + ) class Instance(proto.Message): @@ -1096,11 +1103,16 @@ class Instance(proto.Message): query_insights_config (google.cloud.alloydb_v1beta.types.Instance.QueryInsightsInstanceConfig): Configuration for query insights. read_pool_config (google.cloud.alloydb_v1beta.types.Instance.ReadPoolConfig): - Read pool specific config. + Read pool instance configuration. This is required if the + value of instanceType is READ_POOL. ip_address (str): Output only. The IP address for the Instance. This is the connection endpoint for an end-user application. + public_ip_address (str): + Output only. The public IP addresses for the Instance. This + is available ONLY when enable_public_ip is set. This is the + connection endpoint for an end-user application. reconciling (bool): Output only. Reconciling (https://google.aip.dev/128#reconciliation). Set @@ -1127,6 +1139,14 @@ class Instance(proto.Message): client_connection_config (google.cloud.alloydb_v1beta.types.Instance.ClientConnectionConfig): Optional. Client connection specific configurations + satisfies_pzs (bool): + Output only. Reserved for future use. + psc_instance_config (google.cloud.alloydb_v1beta.types.Instance.PscInstanceConfig): + Optional. The configuration for Private + Service Connect (PSC) for the instance. + network_config (google.cloud.alloydb_v1beta.types.Instance.InstanceNetworkConfig): + Optional. Instance level network + configuration. """ class State(proto.Enum): @@ -1389,6 +1409,140 @@ class ClientConnectionConfig(proto.Message): message="SslConfig", ) + class PscInterfaceConfig(proto.Message): + r"""Configuration for setting up a PSC interface. This + information needs to be provided by the customer. + PSC interfaces will be created and added to VMs via SLM (adding + a network interface will require recreating the VM). For HA + instances this will be done via LDTM. + + Attributes: + consumer_endpoint_ips (MutableSequence[str]): + A list of endpoints in the consumer VPC the + interface might initiate outbound connections + to. This list has to be provided when the PSC + interface is created. + network_attachment (str): + The NetworkAttachment resource created in the consumer VPC + to which the PSC interface will be linked, in the form of: + ``projects/${CONSUMER_PROJECT}/regions/${REGION}/networkAttachments/${NETWORK_ATTACHMENT_NAME}``. + NetworkAttachment has to be provided when the PSC interface + is created. + """ + + consumer_endpoint_ips: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + network_attachment: str = proto.Field( + proto.STRING, + number=2, + ) + + class PscInstanceConfig(proto.Message): + r"""PscInstanceConfig contains PSC related configuration at an + instance level. + + Attributes: + service_attachment_link (str): + Output only. The service attachment created when Private + Service Connect (PSC) is enabled for the instance. The name + of the resource will be in the format of + ``projects//regions//serviceAttachments/`` + allowed_consumer_projects (MutableSequence[str]): + Optional. List of consumer projects that are + allowed to create PSC endpoints to + service-attachments to this instance. + allowed_consumer_networks (MutableSequence[str]): + Optional. List of consumer networks that are + allowed to create PSC endpoints to + service-attachments to this instance. + psc_interface_configs (MutableSequence[google.cloud.alloydb_v1beta.types.Instance.PscInterfaceConfig]): + Optional. Configurations for setting up PSC + interfaces attached to the instance which are + used for outbound connectivity. Only primary + instances can have PSC interface attached. All + the VMs created for the primary instance will + share the same configurations. Currently we only + support 0 or 1 PSC interface. + outgoing_service_attachment_links (MutableSequence[str]): + Optional. List of service attachments that + this instance has created endpoints to connect + with. Currently, only a single outgoing service + attachment is supported per instance. + psc_enabled (bool): + Optional. Whether PSC connectivity is enabled + for this instance. This is populated by + referencing the value from the parent cluster. + """ + + service_attachment_link: str = proto.Field( + proto.STRING, + number=1, + ) + allowed_consumer_projects: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + allowed_consumer_networks: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + psc_interface_configs: MutableSequence[ + "Instance.PscInterfaceConfig" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="Instance.PscInterfaceConfig", + ) + outgoing_service_attachment_links: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + psc_enabled: bool = proto.Field( + proto.BOOL, + number=6, + ) + + class InstanceNetworkConfig(proto.Message): + r"""Metadata related to instance level network configuration. + + Attributes: + authorized_external_networks (MutableSequence[google.cloud.alloydb_v1beta.types.Instance.InstanceNetworkConfig.AuthorizedNetwork]): + Optional. A list of external network + authorized to access this instance. + enable_public_ip (bool): + Optional. Enabling public ip for the + instance. + """ + + class AuthorizedNetwork(proto.Message): + r"""AuthorizedNetwork contains metadata for an authorized + network. + + Attributes: + cidr_range (str): + CIDR range for one authorzied network of the + instance. + """ + + cidr_range: str = proto.Field( + proto.STRING, + number=1, + ) + + authorized_external_networks: MutableSequence[ + "Instance.InstanceNetworkConfig.AuthorizedNetwork" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Instance.InstanceNetworkConfig.AuthorizedNetwork", + ) + enable_public_ip: bool = proto.Field( + proto.BOOL, + number=2, + ) + name: str = proto.Field( proto.STRING, number=1, @@ -1474,6 +1628,10 @@ class ClientConnectionConfig(proto.Message): proto.STRING, number=15, ) + public_ip_address: str = proto.Field( + proto.STRING, + number=27, + ) reconciling: bool = proto.Field( proto.BOOL, number=16, @@ -1497,6 +1655,20 @@ class ClientConnectionConfig(proto.Message): number=23, message=ClientConnectionConfig, ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=24, + ) + psc_instance_config: PscInstanceConfig = proto.Field( + proto.MESSAGE, + number=28, + message=PscInstanceConfig, + ) + network_config: InstanceNetworkConfig = proto.Field( + proto.MESSAGE, + number=29, + message=InstanceNetworkConfig, + ) class ConnectionInfo(proto.Message): @@ -1513,6 +1685,10 @@ class ConnectionInfo(proto.Message): Instance. This is the default IP for the instance and is always created (even if enable_public_ip is set). This is the connection endpoint for an end-user application. + public_ip_address (str): + Output only. The public IP addresses for the Instance. This + is available ONLY when enable_public_ip is set. This is the + connection endpoint for an end-user application. pem_certificate_chain (MutableSequence[str]): Output only. The pem-encoded chain that may be used to verify the X.509 certificate. @@ -1520,6 +1696,9 @@ class ConnectionInfo(proto.Message): to RFC 5246. instance_uid (str): Output only. The unique ID of the Instance. + psc_dns_name (str): + Output only. The DNS name to use with PSC for + the Instance. """ name: str = proto.Field( @@ -1530,6 +1709,10 @@ class ConnectionInfo(proto.Message): proto.STRING, number=2, ) + public_ip_address: str = proto.Field( + proto.STRING, + number=5, + ) pem_certificate_chain: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=3, @@ -1538,6 +1721,10 @@ class ConnectionInfo(proto.Message): proto.STRING, number=4, ) + psc_dns_name: str = proto.Field( + proto.STRING, + number=6, + ) class Backup(proto.Message): @@ -1624,6 +1811,8 @@ class Backup(proto.Message): policy. Once the expiry quantity is over retention, the backup is eligible to be garbage collected. + satisfies_pzs (bool): + Output only. Reserved for future use. database_version (google.cloud.alloydb_v1beta.types.DatabaseVersion): Output only. The database engine major version of the cluster this backup was created @@ -1801,6 +1990,10 @@ class QuantityBasedExpiry(proto.Message): number=20, message=QuantityBasedExpiry, ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=21, + ) database_version: "DatabaseVersion" = proto.Field( proto.ENUM, number=22, @@ -2015,4 +2208,36 @@ class UserType(proto.Enum): ) +class Database(proto.Message): + r"""Message describing Database object. + + Attributes: + name (str): + Identifier. Name of the resource in the form of + ``projects/{project}/locations/{location}/clusters/{cluster}/databases/{database}``. + charset (str): + Optional. Charset for the database. This field can contain + any PostgreSQL supported charset name. Example values + include "UTF8", "SQL_ASCII", etc. + collation (str): + Optional. Collation for the database. + Name of the custom or native collation for + postgres. Example values include "C", "POSIX", + etc + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + charset: str = proto.Field( + proto.STRING, + number=2, + ) + collation: str = proto.Field( + proto.STRING, + number=3, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/types/service.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/types/service.py index cbb773f518a8..94677f255710 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/types/service.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/types/service.py @@ -70,6 +70,8 @@ "CreateUserRequest", "UpdateUserRequest", "DeleteUserRequest", + "ListDatabasesRequest", + "ListDatabasesResponse", }, ) @@ -1684,8 +1686,8 @@ class GenerateClientCertificateRequest(proto.Message): exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). pem_csr (str): - Optional. A pem-encoded X.509 certificate - signing request (CSR). + Optional. A pem-encoded X.509 certificate signing request + (CSR). It is recommended to use public_key instead. cert_duration (google.protobuf.duration_pb2.Duration): Optional. An optional hint to the endpoint to generate the client certificate with the @@ -2136,4 +2138,74 @@ class DeleteUserRequest(proto.Message): ) +class ListDatabasesRequest(proto.Message): + r"""Message for requesting list of Databases. + + Attributes: + parent (str): + Required. Parent value for + ListDatabasesRequest. + page_size (int): + Optional. The maximum number of databases to + return. The service may return fewer than this + value. If unspecified, an appropriate number of + databases will be returned. The max value will + be 2000, values above max will be coerced to + max. + page_token (str): + Optional. A page token, received from a previous + ``ListDatabases`` call. This should be provided to retrieve + the subsequent page. This field is currently not supported, + its value will be ignored if passed. + filter (str): + Optional. Filtering results. + This field is currently not supported, its value + will be ignored if passed. + """ + + 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, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListDatabasesResponse(proto.Message): + r"""Message for response to listing Databases. + + Attributes: + databases (MutableSequence[google.cloud.alloydb_v1beta.types.Database]): + The list of databases + next_page_token (str): + A token identifying the next page of results + the server should return. If this field is + omitted, there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + databases: MutableSequence[resources.Database] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.Database, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_databases_async.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_databases_async.py new file mode 100644 index 000000000000..9cbc3f1e5626 --- /dev/null +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_databases_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListDatabases +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_ListDatabases_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 alloydb_v1beta + + +async def sample_list_databases(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListDatabasesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_databases(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_ListDatabases_async] diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_databases_sync.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_databases_sync.py new file mode 100644 index 000000000000..caf62381ca67 --- /dev/null +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_list_databases_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListDatabases +# 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-alloydb + + +# [START alloydb_v1beta_generated_AlloyDBAdmin_ListDatabases_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 alloydb_v1beta + + +def sample_list_databases(): + # Create a client + client = alloydb_v1beta.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1beta.ListDatabasesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_databases(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END alloydb_v1beta_generated_AlloyDBAdmin_ListDatabases_sync] 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 681eb4cdfbd5..ed3c3bae050c 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.9" + "version": "0.3.10" }, "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 c36dfcd991b5..005a37e64c31 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.9" + "version": "0.3.10" }, "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 0cf5ee696f12..7ad4bcd00c73 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.9" + "version": "0.3.10" }, "snippets": [ { @@ -3482,6 +3482,167 @@ ], "title": "alloydb_v1beta_generated_alloy_db_admin_list_clusters_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminAsyncClient.list_databases", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.ListDatabases", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListDatabases" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.ListDatabasesRequest" + }, + { + "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.alloydb_v1beta.services.alloy_db_admin.pagers.ListDatabasesAsyncPager", + "shortName": "list_databases" + }, + "description": "Sample for ListDatabases", + "file": "alloydb_v1beta_generated_alloy_db_admin_list_databases_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_ListDatabases_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": "alloydb_v1beta_generated_alloy_db_admin_list_databases_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1beta.AlloyDBAdminClient.list_databases", + "method": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin.ListDatabases", + "service": { + "fullName": "google.cloud.alloydb.v1beta.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListDatabases" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1beta.types.ListDatabasesRequest" + }, + { + "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.alloydb_v1beta.services.alloy_db_admin.pagers.ListDatabasesPager", + "shortName": "list_databases" + }, + "description": "Sample for ListDatabases", + "file": "alloydb_v1beta_generated_alloy_db_admin_list_databases_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1beta_generated_AlloyDBAdmin_ListDatabases_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": "alloydb_v1beta_generated_alloy_db_admin_list_databases_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-alloydb/scripts/fixup_alloydb_v1beta_keywords.py b/packages/google-cloud-alloydb/scripts/fixup_alloydb_v1beta_keywords.py index 14b3ca7826ae..d6ed3ae54c7d 100644 --- a/packages/google-cloud-alloydb/scripts/fixup_alloydb_v1beta_keywords.py +++ b/packages/google-cloud-alloydb/scripts/fixup_alloydb_v1beta_keywords.py @@ -60,6 +60,7 @@ class alloydbCallTransformer(cst.CSTTransformer): 'inject_fault': ('fault_type', 'name', 'request_id', 'validate_only', ), 'list_backups': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_clusters': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_databases': ('parent', 'page_size', 'page_token', 'filter', ), 'list_instances': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_supported_database_flags': ('parent', 'page_size', 'page_token', ), 'list_users': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), diff --git a/packages/google-cloud-alloydb/setup.py b/packages/google-cloud-alloydb/setup.py index 892b72d47378..4a8d87997537 100644 --- a/packages/google-cloud-alloydb/setup.py +++ b/packages/google-cloud-alloydb/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", 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 3ea1306bc28f..6e759daf3162 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 @@ -3636,6 +3636,7 @@ def test_get_instance(request_type, transport: str = "grpc"): availability_type=resources.Instance.AvailabilityType.ZONAL, gce_zone="gce_zone_value", ip_address="ip_address_value", + public_ip_address="public_ip_address_value", reconciling=True, etag="etag_value", satisfies_pzi=True, @@ -3658,6 +3659,7 @@ def test_get_instance(request_type, transport: str = "grpc"): assert response.availability_type == resources.Instance.AvailabilityType.ZONAL assert response.gce_zone == "gce_zone_value" assert response.ip_address == "ip_address_value" + assert response.public_ip_address == "public_ip_address_value" assert response.reconciling is True assert response.etag == "etag_value" assert response.satisfies_pzi is True @@ -3706,6 +3708,7 @@ async def test_get_instance_async( availability_type=resources.Instance.AvailabilityType.ZONAL, gce_zone="gce_zone_value", ip_address="ip_address_value", + public_ip_address="public_ip_address_value", reconciling=True, etag="etag_value", satisfies_pzi=True, @@ -3729,6 +3732,7 @@ async def test_get_instance_async( assert response.availability_type == resources.Instance.AvailabilityType.ZONAL assert response.gce_zone == "gce_zone_value" assert response.ip_address == "ip_address_value" + assert response.public_ip_address == "public_ip_address_value" assert response.reconciling is True assert response.etag == "etag_value" assert response.satisfies_pzi is True @@ -7845,6 +7849,7 @@ def test_get_connection_info(request_type, transport: str = "grpc"): public_ip_address="public_ip_address_value", pem_certificate_chain=["pem_certificate_chain_value"], instance_uid="instance_uid_value", + psc_dns_name="psc_dns_name_value", ) response = client.get_connection_info(request) @@ -7860,6 +7865,7 @@ def test_get_connection_info(request_type, transport: str = "grpc"): assert response.public_ip_address == "public_ip_address_value" assert response.pem_certificate_chain == ["pem_certificate_chain_value"] assert response.instance_uid == "instance_uid_value" + assert response.psc_dns_name == "psc_dns_name_value" def test_get_connection_info_empty_call(): @@ -7905,6 +7911,7 @@ async def test_get_connection_info_async( public_ip_address="public_ip_address_value", pem_certificate_chain=["pem_certificate_chain_value"], instance_uid="instance_uid_value", + psc_dns_name="psc_dns_name_value", ) ) response = await client.get_connection_info(request) @@ -7921,6 +7928,7 @@ async def test_get_connection_info_async( assert response.public_ip_address == "public_ip_address_value" assert response.pem_certificate_chain == ["pem_certificate_chain_value"] assert response.instance_uid == "instance_uid_value" + assert response.psc_dns_name == "psc_dns_name_value" @pytest.mark.asyncio @@ -12950,6 +12958,7 @@ def test_get_instance_rest(request_type): availability_type=resources.Instance.AvailabilityType.ZONAL, gce_zone="gce_zone_value", ip_address="ip_address_value", + public_ip_address="public_ip_address_value", reconciling=True, etag="etag_value", satisfies_pzi=True, @@ -12977,6 +12986,7 @@ def test_get_instance_rest(request_type): assert response.availability_type == resources.Instance.AvailabilityType.ZONAL assert response.gce_zone == "gce_zone_value" assert response.ip_address == "ip_address_value" + assert response.public_ip_address == "public_ip_address_value" assert response.reconciling is True assert response.etag == "etag_value" assert response.satisfies_pzi is True @@ -13254,6 +13264,7 @@ def test_create_instance_rest(request_type): }, "read_pool_config": {"node_count": 1070}, "ip_address": "ip_address_value", + "public_ip_address": "public_ip_address_value", "reconciling": True, "etag": "etag_value", "annotations": {}, @@ -13690,6 +13701,7 @@ def test_create_secondary_instance_rest(request_type): }, "read_pool_config": {"node_count": 1070}, "ip_address": "ip_address_value", + "public_ip_address": "public_ip_address_value", "reconciling": True, "etag": "etag_value", "annotations": {}, @@ -14133,6 +14145,7 @@ def test_batch_create_instances_rest(request_type): }, "read_pool_config": {"node_count": 1070}, "ip_address": "ip_address_value", + "public_ip_address": "public_ip_address_value", "reconciling": True, "etag": "etag_value", "annotations": {}, @@ -14495,6 +14508,7 @@ def test_update_instance_rest(request_type): }, "read_pool_config": {"node_count": 1070}, "ip_address": "ip_address_value", + "public_ip_address": "public_ip_address_value", "reconciling": True, "etag": "etag_value", "annotations": {}, @@ -18256,6 +18270,7 @@ def test_get_connection_info_rest(request_type): public_ip_address="public_ip_address_value", pem_certificate_chain=["pem_certificate_chain_value"], instance_uid="instance_uid_value", + psc_dns_name="psc_dns_name_value", ) # Wrap the value into a proper Response obj @@ -18276,6 +18291,7 @@ def test_get_connection_info_rest(request_type): assert response.public_ip_address == "public_ip_address_value" assert response.pem_certificate_chain == ["pem_certificate_chain_value"] assert response.instance_uid == "instance_uid_value" + assert response.psc_dns_name == "psc_dns_name_value" def test_get_connection_info_rest_required_fields( 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 1afe1791ef0b..df39e6edd539 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 @@ -1569,6 +1569,7 @@ def test_get_cluster(request_type, transport: str = "grpc"): network="network_value", etag="etag_value", reconciling=True, + satisfies_pzs=True, ) response = client.get_cluster(request) @@ -1588,6 +1589,7 @@ def test_get_cluster(request_type, transport: str = "grpc"): assert response.network == "network_value" assert response.etag == "etag_value" assert response.reconciling is True + assert response.satisfies_pzs is True def test_get_cluster_empty_call(): @@ -1633,6 +1635,7 @@ async def test_get_cluster_async( network="network_value", etag="etag_value", reconciling=True, + satisfies_pzs=True, ) ) response = await client.get_cluster(request) @@ -1653,6 +1656,7 @@ async def test_get_cluster_async( assert response.network == "network_value" assert response.etag == "etag_value" assert response.reconciling is True + assert response.satisfies_pzs is True @pytest.mark.asyncio @@ -3628,8 +3632,10 @@ def test_get_instance(request_type, transport: str = "grpc"): availability_type=resources.Instance.AvailabilityType.ZONAL, gce_zone="gce_zone_value", ip_address="ip_address_value", + public_ip_address="public_ip_address_value", reconciling=True, etag="etag_value", + satisfies_pzs=True, ) response = client.get_instance(request) @@ -3648,8 +3654,10 @@ def test_get_instance(request_type, transport: str = "grpc"): assert response.availability_type == resources.Instance.AvailabilityType.ZONAL assert response.gce_zone == "gce_zone_value" assert response.ip_address == "ip_address_value" + assert response.public_ip_address == "public_ip_address_value" assert response.reconciling is True assert response.etag == "etag_value" + assert response.satisfies_pzs is True def test_get_instance_empty_call(): @@ -3694,8 +3702,10 @@ async def test_get_instance_async( availability_type=resources.Instance.AvailabilityType.ZONAL, gce_zone="gce_zone_value", ip_address="ip_address_value", + public_ip_address="public_ip_address_value", reconciling=True, etag="etag_value", + satisfies_pzs=True, ) ) response = await client.get_instance(request) @@ -3715,8 +3725,10 @@ async def test_get_instance_async( assert response.availability_type == resources.Instance.AvailabilityType.ZONAL assert response.gce_zone == "gce_zone_value" assert response.ip_address == "ip_address_value" + assert response.public_ip_address == "public_ip_address_value" assert response.reconciling is True assert response.etag == "etag_value" + assert response.satisfies_pzs is True @pytest.mark.asyncio @@ -6145,6 +6157,7 @@ def test_get_backup(request_type, transport: str = "grpc"): reconciling=True, etag="etag_value", size_bytes=1089, + satisfies_pzs=True, database_version=resources.DatabaseVersion.POSTGRES_13, ) response = client.get_backup(request) @@ -6167,6 +6180,7 @@ def test_get_backup(request_type, transport: str = "grpc"): assert response.reconciling is True assert response.etag == "etag_value" assert response.size_bytes == 1089 + assert response.satisfies_pzs is True assert response.database_version == resources.DatabaseVersion.POSTGRES_13 @@ -6215,6 +6229,7 @@ async def test_get_backup_async( reconciling=True, etag="etag_value", size_bytes=1089, + satisfies_pzs=True, database_version=resources.DatabaseVersion.POSTGRES_13, ) ) @@ -6238,6 +6253,7 @@ async def test_get_backup_async( assert response.reconciling is True assert response.etag == "etag_value" assert response.size_bytes == 1089 + assert response.satisfies_pzs is True assert response.database_version == resources.DatabaseVersion.POSTGRES_13 @@ -7818,8 +7834,10 @@ def test_get_connection_info(request_type, transport: str = "grpc"): call.return_value = resources.ConnectionInfo( name="name_value", ip_address="ip_address_value", + public_ip_address="public_ip_address_value", pem_certificate_chain=["pem_certificate_chain_value"], instance_uid="instance_uid_value", + psc_dns_name="psc_dns_name_value", ) response = client.get_connection_info(request) @@ -7832,8 +7850,10 @@ def test_get_connection_info(request_type, transport: str = "grpc"): assert isinstance(response, resources.ConnectionInfo) assert response.name == "name_value" assert response.ip_address == "ip_address_value" + assert response.public_ip_address == "public_ip_address_value" assert response.pem_certificate_chain == ["pem_certificate_chain_value"] assert response.instance_uid == "instance_uid_value" + assert response.psc_dns_name == "psc_dns_name_value" def test_get_connection_info_empty_call(): @@ -7876,8 +7896,10 @@ async def test_get_connection_info_async( resources.ConnectionInfo( name="name_value", ip_address="ip_address_value", + public_ip_address="public_ip_address_value", pem_certificate_chain=["pem_certificate_chain_value"], instance_uid="instance_uid_value", + psc_dns_name="psc_dns_name_value", ) ) response = await client.get_connection_info(request) @@ -7891,8 +7913,10 @@ async def test_get_connection_info_async( assert isinstance(response, resources.ConnectionInfo) assert response.name == "name_value" assert response.ip_address == "ip_address_value" + assert response.public_ip_address == "public_ip_address_value" assert response.pem_certificate_chain == ["pem_certificate_chain_value"] assert response.instance_uid == "instance_uid_value" + assert response.psc_dns_name == "psc_dns_name_value" @pytest.mark.asyncio @@ -9447,6 +9471,428 @@ async def test_delete_user_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + service.ListDatabasesRequest, + dict, + ], +) +def test_list_databases(request_type, transport: str = "grpc"): + client = AlloyDBAdminClient( + 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_databases), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListDatabasesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_databases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListDatabasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDatabasesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_databases_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_databases), "__call__") as call: + client.list_databases() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListDatabasesRequest() + + +@pytest.mark.asyncio +async def test_list_databases_async( + transport: str = "grpc_asyncio", request_type=service.ListDatabasesRequest +): + client = AlloyDBAdminAsyncClient( + 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_databases), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListDatabasesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_databases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListDatabasesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDatabasesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_databases_async_from_dict(): + await test_list_databases_async(request_type=dict) + + +def test_list_databases_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListDatabasesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_databases), "__call__") as call: + call.return_value = service.ListDatabasesResponse() + client.list_databases(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_databases_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListDatabasesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_databases), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListDatabasesResponse() + ) + await client.list_databases(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_databases_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_databases), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListDatabasesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_databases( + 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_databases_flattened_error(): + client = AlloyDBAdminClient( + 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_databases( + service.ListDatabasesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_databases_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_databases), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListDatabasesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListDatabasesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_databases( + 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_databases_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_databases( + service.ListDatabasesRequest(), + parent="parent_value", + ) + + +def test_list_databases_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_databases), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + resources.Database(), + ], + next_page_token="abc", + ), + service.ListDatabasesResponse( + databases=[], + next_page_token="def", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + ], + next_page_token="ghi", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_databases(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Database) for i in results) + + +def test_list_databases_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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_databases), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + resources.Database(), + ], + next_page_token="abc", + ), + service.ListDatabasesResponse( + databases=[], + next_page_token="def", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + ], + next_page_token="ghi", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + ], + ), + RuntimeError, + ) + pages = list(client.list_databases(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_databases_async_pager(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_databases), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + resources.Database(), + ], + next_page_token="abc", + ), + service.ListDatabasesResponse( + databases=[], + next_page_token="def", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + ], + next_page_token="ghi", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_databases( + 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, resources.Database) for i in responses) + + +@pytest.mark.asyncio +async def test_list_databases_async_pages(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_databases), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + resources.Database(), + ], + next_page_token="abc", + ), + service.ListDatabasesResponse( + databases=[], + next_page_token="def", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + ], + next_page_token="ghi", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + ], + ), + 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_databases(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", [ @@ -9454,46 +9900,401 @@ async def test_delete_user_flattened_error_async(): dict, ], ) -def test_list_clusters_rest(request_type): +def test_list_clusters_rest(request_type): + client = AlloyDBAdminClient( + 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 = service.ListClustersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = service.ListClustersResponse.pb(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_clusters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_clusters_rest_required_fields(request_type=service.ListClustersRequest): + transport_class = transports.AlloyDBAdminRestTransport + + 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_clusters._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_clusters._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 = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListClustersResponse() + # 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 = service.ListClustersResponse.pb(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_clusters(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_clusters_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_clusters._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_clusters_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(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.AlloyDBAdminRestInterceptor, "post_list_clusters" + ) as post, mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "pre_list_clusters" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListClustersRequest.pb(service.ListClustersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListClustersResponse.to_json( + service.ListClustersResponse() + ) + + request = service.ListClustersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListClustersResponse() + + client.list_clusters( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_clusters_rest_bad_request( + transport: str = "rest", request_type=service.ListClustersRequest +): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_clusters(request) + + +def test_list_clusters_rest_flattened(): + client = AlloyDBAdminClient( + 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 = service.ListClustersResponse() + + # 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 = service.ListClustersResponse.pb(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_clusters(**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/*}/clusters" + % client.transport._host, + args[1], + ) + + +def test_list_clusters_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + 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_clusters( + service.ListClustersRequest(), + parent="parent_value", + ) + + +def test_list_clusters_rest_pager(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token="abc", + ), + service.ListClustersResponse( + clusters=[], + next_page_token="def", + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token="ghi", + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListClustersResponse.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_clusters(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Cluster) for i in results) + + pages = list(client.list_clusters(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetClusterRequest, + dict, + ], +) +def test_get_cluster_rest(request_type): client = AlloyDBAdminClient( 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/clusters/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 = service.ListClustersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + return_value = resources.Cluster( + name="name_value", + display_name="display_name_value", + uid="uid_value", + state=resources.Cluster.State.READY, + cluster_type=resources.Cluster.ClusterType.PRIMARY, + database_version=resources.DatabaseVersion.POSTGRES_13, + network="network_value", + etag="etag_value", + reconciling=True, + satisfies_pzs=True, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListClustersResponse.pb(return_value) + return_value = resources.Cluster.pb(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_clusters(request) + response = client.get_cluster(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClustersPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, resources.Cluster) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.uid == "uid_value" + assert response.state == resources.Cluster.State.READY + assert response.cluster_type == resources.Cluster.ClusterType.PRIMARY + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + assert response.network == "network_value" + assert response.etag == "etag_value" + assert response.reconciling is True + assert response.satisfies_pzs is True -def test_list_clusters_rest_required_fields(request_type=service.ListClustersRequest): +def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -9504,30 +10305,23 @@ def test_list_clusters_rest_required_fields(request_type=service.ListClustersReq unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_clusters._get_unset_required_fields(jsonified_request) + ).get_cluster._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" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_clusters._get_unset_required_fields(jsonified_request) + ).get_cluster._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", - ) - ) + assert not set(unset_fields) - set(("view",)) 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 "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9536,7 +10330,7 @@ def test_list_clusters_rest_required_fields(request_type=service.ListClustersReq request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListClustersResponse() + return_value = resources.Cluster() # 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 @@ -9557,40 +10351,30 @@ def test_list_clusters_rest_required_fields(request_type=service.ListClustersReq response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListClustersResponse.pb(return_value) + return_value = resources.Cluster.pb(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_clusters(request) + response = client.get_cluster(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_clusters_rest_unset_required_fields(): +def test_get_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_clusters._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.get_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("view",)) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_clusters_rest_interceptors(null_interceptor): +def test_get_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9603,13 +10387,13 @@ def test_list_clusters_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_list_clusters" + transports.AlloyDBAdminRestInterceptor, "post_get_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_list_clusters" + transports.AlloyDBAdminRestInterceptor, "pre_get_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListClustersRequest.pb(service.ListClustersRequest()) + pb_message = service.GetClusterRequest.pb(service.GetClusterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9620,19 +10404,17 @@ def test_list_clusters_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = service.ListClustersResponse.to_json( - service.ListClustersResponse() - ) + req.return_value._content = resources.Cluster.to_json(resources.Cluster()) - request = service.ListClustersRequest() + request = service.GetClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListClustersResponse() + post.return_value = resources.Cluster() - client.list_clusters( + client.get_cluster( request, metadata=[ ("key", "val"), @@ -9644,8 +10426,8 @@ def test_list_clusters_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_clusters_rest_bad_request( - transport: str = "rest", request_type=service.ListClustersRequest +def test_get_cluster_rest_bad_request( + transport: str = "rest", request_type=service.GetClusterRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9653,7 +10435,7 @@ def test_list_clusters_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9665,10 +10447,10 @@ def test_list_clusters_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_clusters(request) + client.get_cluster(request) -def test_list_clusters_rest_flattened(): +def test_get_cluster_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -9677,14 +10459,14 @@ def test_list_clusters_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 = service.ListClustersResponse() + return_value = resources.Cluster() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {"name": "projects/sample1/locations/sample2/clusters/sample3"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) @@ -9692,25 +10474,25 @@ def test_list_clusters_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListClustersResponse.pb(return_value) + return_value = resources.Cluster.pb(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_clusters(**mock_args) + client.get_cluster(**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/*}/clusters" + "%s/v1beta/{name=projects/*/locations/*/clusters/*}" % client.transport._host, args[1], ) -def test_list_clusters_rest_flattened_error(transport: str = "rest"): +def test_get_cluster_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9719,134 +10501,198 @@ def test_list_clusters_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.list_clusters( - service.ListClustersRequest(), - parent="parent_value", + client.get_cluster( + service.GetClusterRequest(), + name="name_value", ) -def test_list_clusters_rest_pager(transport: str = "rest"): +def test_get_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateClusterRequest, + dict, + ], +) +def test_create_cluster_rest(request_type): client = AlloyDBAdminClient( 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 = ( - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - resources.Cluster(), - resources.Cluster(), - ], - next_page_token="abc", - ), - service.ListClustersResponse( - clusters=[], - next_page_token="def", - ), - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - ], - next_page_token="ghi", - ), - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - resources.Cluster(), - ], - ), - ) - # Two responses for two calls - response = response + response + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["cluster"] = { + "backup_source": { + "backup_uid": "backup_uid_value", + "backup_name": "backup_name_value", + }, + "migration_source": { + "host_port": "host_port_value", + "reference_id": "reference_id_value", + "source_type": 1, + }, + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "cluster_type": 1, + "database_version": 1, + "network_config": { + "network": "network_value", + "allocated_ip_range": "allocated_ip_range_value", + }, + "network": "network_value", + "etag": "etag_value", + "annotations": {}, + "reconciling": True, + "initial_user": {"user": "user_value", "password": "password_value"}, + "automated_backup_policy": { + "weekly_schedule": { + "start_times": [ + {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} + ], + "days_of_week": [1], + }, + "time_based_retention": { + "retention_period": {"seconds": 751, "nanos": 543} + }, + "quantity_based_retention": {"count": 553}, + "enabled": True, + "backup_window": {}, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "location": "location_value", + "labels": {}, + }, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + "encryption_config": {}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "continuous_backup_config": { + "enabled": True, + "recovery_window_days": 2166, + "encryption_config": {}, + }, + "continuous_backup_info": { + "encryption_info": {}, + "enabled_time": {}, + "schedule": [1], + "earliest_restorable_time": {}, + }, + "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, + "primary_config": { + "secondary_cluster_names": [ + "secondary_cluster_names_value1", + "secondary_cluster_names_value2", + ] + }, + "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 = service.CreateClusterRequest.meta.fields["cluster"] - # Wrap the values into proper Response objs - response = tuple(service.ListClustersResponse.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 + 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 = [] - sample_request = {"parent": "projects/sample1/locations/sample2"} + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - pager = client.list_clusters(request=sample_request) + 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 - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Cluster) for i in results) + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] - pages = list(client.list_clusters(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + 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["cluster"].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 -@pytest.mark.parametrize( - "request_type", - [ - service.GetClusterRequest, - dict, - ], -) -def test_get_cluster_rest(request_type): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + 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, + } + ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + # 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["cluster"][field])): + del request_init["cluster"][field][i][subfield] + else: + del request_init["cluster"][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 = resources.Cluster( - name="name_value", - display_name="display_name_value", - uid="uid_value", - state=resources.Cluster.State.READY, - cluster_type=resources.Cluster.ClusterType.PRIMARY, - database_version=resources.DatabaseVersion.POSTGRES_13, - network="network_value", - etag="etag_value", - reconciling=True, - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Cluster.pb(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_cluster(request) + response = client.create_cluster(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Cluster) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.uid == "uid_value" - assert response.state == resources.Cluster.State.READY - assert response.cluster_type == resources.Cluster.ClusterType.PRIMARY - assert response.database_version == resources.DatabaseVersion.POSTGRES_13 - assert response.network == "network_value" - assert response.etag == "etag_value" - assert response.reconciling is True + assert response.operation.name == "operations/spam" -def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest): +def test_create_cluster_rest_required_fields(request_type=service.CreateClusterRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["cluster_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -9854,26 +10700,38 @@ def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest ) # verify fields with default values are dropped + assert "clusterId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_cluster._get_unset_required_fields(jsonified_request) + ).create_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == request_init["cluster_id"] - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["clusterId"] = "cluster_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_cluster._get_unset_required_fields(jsonified_request) + ).create_cluster._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("view",)) + assert not set(unset_fields) - set( + ( + "cluster_id", + "request_id", + "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 "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == "cluster_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9882,7 +10740,7 @@ def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Cluster() + 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 @@ -9894,39 +10752,58 @@ def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest 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 = resources.Cluster.pb(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_cluster(request) + response = client.create_cluster(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "clusterId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_cluster_rest_unset_required_fields(): +def test_create_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("view",)) & set(("name",))) + unset_fields = transport.create_cluster._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "clusterId", + "requestId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "clusterId", + "cluster", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_cluster_rest_interceptors(null_interceptor): +def test_create_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9939,13 +10816,15 @@ def test_get_cluster_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_get_cluster" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_create_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_get_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_create_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.GetClusterRequest.pb(service.GetClusterRequest()) + pb_message = service.CreateClusterRequest.pb(service.CreateClusterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9956,17 +10835,19 @@ def test_get_cluster_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.Cluster.to_json(resources.Cluster()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) - request = service.GetClusterRequest() + request = service.CreateClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Cluster() + post.return_value = operations_pb2.Operation() - client.get_cluster( + client.create_cluster( request, metadata=[ ("key", "val"), @@ -9978,8 +10859,8 @@ def test_get_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_cluster_rest_bad_request( - transport: str = "rest", request_type=service.GetClusterRequest +def test_create_cluster_rest_bad_request( + transport: str = "rest", request_type=service.CreateClusterRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9987,7 +10868,7 @@ def test_get_cluster_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/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. @@ -9999,10 +10880,10 @@ def test_get_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_cluster(request) + client.create_cluster(request) -def test_get_cluster_rest_flattened(): +def test_create_cluster_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -10011,40 +10892,42 @@ def test_get_cluster_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 = resources.Cluster() + 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/clusters/sample3"} + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + cluster_id="cluster_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 = resources.Cluster.pb(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_cluster(**mock_args) + client.create_cluster(**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/*/clusters/*}" + "%s/v1beta/{parent=projects/*/locations/*}/clusters" % client.transport._host, args[1], ) -def test_get_cluster_rest_flattened_error(transport: str = "rest"): +def test_create_cluster_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10053,13 +10936,17 @@ def test_get_cluster_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.get_cluster( - service.GetClusterRequest(), - name="name_value", + client.create_cluster( + service.CreateClusterRequest(), + parent="parent_value", + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + cluster_id="cluster_id_value", ) -def test_get_cluster_rest_error(): +def test_create_cluster_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -10068,18 +10955,20 @@ def test_get_cluster_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.CreateClusterRequest, + service.UpdateClusterRequest, dict, ], ) -def test_create_cluster_rest(request_type): +def test_update_cluster_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} + } request_init["cluster"] = { "backup_source": { "backup_uid": "backup_uid_value", @@ -10090,7 +10979,7 @@ def test_create_cluster_rest(request_type): "reference_id": "reference_id_value", "source_type": 1, }, - "name": "name_value", + "name": "projects/sample1/locations/sample2/clusters/sample3", "display_name": "display_name_value", "uid": "uid_value", "create_time": {"seconds": 751, "nanos": 543}, @@ -10150,13 +11039,14 @@ def test_create_cluster_rest(request_type): "secondary_cluster_names_value2", ] }, + "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 = service.CreateClusterRequest.meta.fields["cluster"] + test_field = service.UpdateClusterRequest.meta.fields["cluster"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -10232,18 +11122,16 @@ def get_message_fields(field): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_cluster(request) + response = client.update_cluster(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_create_cluster_rest_required_fields(request_type=service.CreateClusterRequest): +def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" - request_init["cluster_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -10251,38 +11139,29 @@ def test_create_cluster_rest_required_fields(request_type=service.CreateClusterR ) # verify fields with default values are dropped - assert "clusterId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_cluster._get_unset_required_fields(jsonified_request) + ).update_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == request_init["cluster_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["clusterId"] = "cluster_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_cluster._get_unset_required_fields(jsonified_request) + ).update_cluster._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "cluster_id", + "allow_missing", "request_id", + "update_mask", "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 "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == "cluster_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10303,7 +11182,7 @@ def test_create_cluster_rest_required_fields(request_type=service.CreateClusterR 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 @@ -10316,45 +11195,34 @@ def test_create_cluster_rest_required_fields(request_type=service.CreateClusterR response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_cluster(request) + response = client.update_cluster(request) - expected_params = [ - ( - "clusterId", - "", - ), - ("$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_create_cluster_rest_unset_required_fields(): +def test_update_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_cluster._get_unset_required_fields({}) + unset_fields = transport.update_cluster._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "clusterId", + "allowMissing", "requestId", + "updateMask", "validateOnly", ) ) - & set( - ( - "parent", - "clusterId", - "cluster", - ) - ) + & set(("cluster",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_cluster_rest_interceptors(null_interceptor): +def test_update_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10369,13 +11237,13 @@ def test_create_cluster_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_create_cluster" + transports.AlloyDBAdminRestInterceptor, "post_update_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_create_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_update_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.CreateClusterRequest.pb(service.CreateClusterRequest()) + pb_message = service.UpdateClusterRequest.pb(service.UpdateClusterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10390,7 +11258,7 @@ def test_create_cluster_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.CreateClusterRequest() + request = service.UpdateClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -10398,7 +11266,7 @@ def test_create_cluster_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_cluster( + client.update_cluster( request, metadata=[ ("key", "val"), @@ -10410,8 +11278,8 @@ def test_create_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_cluster_rest_bad_request( - transport: str = "rest", request_type=service.CreateClusterRequest +def test_update_cluster_rest_bad_request( + transport: str = "rest", request_type=service.UpdateClusterRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10419,7 +11287,9 @@ def test_create_cluster_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10431,10 +11301,10 @@ def test_create_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_cluster(request) + client.update_cluster(request) -def test_create_cluster_rest_flattened(): +def test_update_cluster_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -10446,218 +11316,78 @@ def test_create_cluster_rest_flattened(): 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", - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - cluster_id="cluster_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_cluster(**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/*}/clusters" - % client.transport._host, - args[1], - ) - - -def test_create_cluster_rest_flattened_error(transport: str = "rest"): - client = AlloyDBAdminClient( - 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_cluster( - service.CreateClusterRequest(), - parent="parent_value", - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - cluster_id="cluster_id_value", - ) - - -def test_create_cluster_rest_error(): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.UpdateClusterRequest, - dict, - ], -) -def test_update_cluster_rest(request_type): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + sample_request = { + "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} + } - # send a request that will satisfy transcoding - request_init = { - "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} - } - request_init["cluster"] = { - "backup_source": { - "backup_uid": "backup_uid_value", - "backup_name": "backup_name_value", - }, - "migration_source": { - "host_port": "host_port_value", - "reference_id": "reference_id_value", - "source_type": 1, - }, - "name": "projects/sample1/locations/sample2/clusters/sample3", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "cluster_type": 1, - "database_version": 1, - "network_config": { - "network": "network_value", - "allocated_ip_range": "allocated_ip_range_value", - }, - "network": "network_value", - "etag": "etag_value", - "annotations": {}, - "reconciling": True, - "initial_user": {"user": "user_value", "password": "password_value"}, - "automated_backup_policy": { - "weekly_schedule": { - "start_times": [ - {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} - ], - "days_of_week": [1], - }, - "time_based_retention": { - "retention_period": {"seconds": 751, "nanos": 543} - }, - "quantity_based_retention": {"count": 553}, - "enabled": True, - "backup_window": {}, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "location": "location_value", - "labels": {}, - }, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - "encryption_config": {}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "continuous_backup_config": { - "enabled": True, - "recovery_window_days": 2166, - "encryption_config": {}, - }, - "continuous_backup_info": { - "encryption_info": {}, - "enabled_time": {}, - "schedule": [1], - "earliest_restorable_time": {}, - }, - "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, - "primary_config": { - "secondary_cluster_names": [ - "secondary_cluster_names_value1", - "secondary_cluster_names_value2", - ] - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # get truthy value for each flattened field + mock_args = dict( + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) - # Determine if the message type is proto-plus or protobuf - test_field = service.UpdateClusterRequest.meta.fields["cluster"] + # 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 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 = [] + client.update_cluster(**mock_args) - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + # 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/{cluster.name=projects/*/locations/*/clusters/*}" + % client.transport._host, + args[1], + ) - 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) - ] +def test_update_cluster_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - subfields_not_in_runtime = [] + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_cluster( + service.UpdateClusterRequest(), + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) - # 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["cluster"].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, - } - ) +def test_update_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - # 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["cluster"][field])): - del request_init["cluster"][field][i][subfield] - else: - del request_init["cluster"][field][subfield] + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteClusterRequest, + dict, + ], +) +def test_delete_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -10672,16 +11402,17 @@ def get_message_fields(field): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_cluster(request) + response = client.delete_cluster(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterRequest): +def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -10692,26 +11423,30 @@ def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterR unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_cluster._get_unset_required_fields(jsonified_request) + ).delete_cluster._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_cluster._get_unset_required_fields(jsonified_request) + ).delete_cluster._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", + "force", "request_id", - "update_mask", "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 = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10732,10 +11467,9 @@ def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterR pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -10745,34 +11479,34 @@ def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterR response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_cluster(request) + response = client.delete_cluster(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_cluster_rest_unset_required_fields(): +def test_delete_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_cluster._get_unset_required_fields({}) + unset_fields = transport.delete_cluster._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "allowMissing", + "etag", + "force", "requestId", - "updateMask", "validateOnly", ) ) - & set(("cluster",)) + & set(("name",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_cluster_rest_interceptors(null_interceptor): +def test_delete_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10787,13 +11521,13 @@ def test_update_cluster_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_update_cluster" + transports.AlloyDBAdminRestInterceptor, "post_delete_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_update_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_delete_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.UpdateClusterRequest.pb(service.UpdateClusterRequest()) + pb_message = service.DeleteClusterRequest.pb(service.DeleteClusterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10808,7 +11542,7 @@ def test_update_cluster_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.UpdateClusterRequest() + request = service.DeleteClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -10816,7 +11550,7 @@ def test_update_cluster_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.update_cluster( + client.delete_cluster( request, metadata=[ ("key", "val"), @@ -10828,8 +11562,8 @@ def test_update_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_cluster_rest_bad_request( - transport: str = "rest", request_type=service.UpdateClusterRequest +def test_delete_cluster_rest_bad_request( + transport: str = "rest", request_type=service.DeleteClusterRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10837,9 +11571,7 @@ def test_update_cluster_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} - } + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10851,10 +11583,10 @@ def test_update_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_cluster(request) + client.delete_cluster(request) -def test_update_cluster_rest_flattened(): +def test_delete_cluster_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -10866,16 +11598,11 @@ def test_update_cluster_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = { - "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} - } + sample_request = {"name": "projects/sample1/locations/sample2/clusters/sample3"} # get truthy value for each flattened field mock_args = dict( - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -10886,20 +11613,20 @@ def test_update_cluster_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_cluster(**mock_args) + client.delete_cluster(**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/{cluster.name=projects/*/locations/*/clusters/*}" + "%s/v1beta/{name=projects/*/locations/*/clusters/*}" % client.transport._host, args[1], ) -def test_update_cluster_rest_flattened_error(transport: str = "rest"): +def test_delete_cluster_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10908,16 +11635,13 @@ def test_update_cluster_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_cluster( - service.UpdateClusterRequest(), - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_cluster( + service.DeleteClusterRequest(), + name="name_value", ) -def test_update_cluster_rest_error(): +def test_delete_cluster_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -10926,11 +11650,11 @@ def test_update_cluster_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.DeleteClusterRequest, + service.PromoteClusterRequest, dict, ], ) -def test_delete_cluster_rest(request_type): +def test_promote_cluster_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -10952,13 +11676,15 @@ def test_delete_cluster_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_cluster(request) + response = client.promote_cluster(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterRequest): +def test_promote_cluster_rest_required_fields( + request_type=service.PromoteClusterRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} @@ -10973,7 +11699,7 @@ def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterR unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_cluster._get_unset_required_fields(jsonified_request) + ).promote_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -10982,16 +11708,7 @@ def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterR unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "etag", - "force", - "request_id", - "validate_only", - ) - ) + ).promote_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -11017,9 +11734,10 @@ def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterR 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() @@ -11029,34 +11747,24 @@ def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterR response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_cluster(request) + response = client.promote_cluster(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_cluster_rest_unset_required_fields(): +def test_promote_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_cluster._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "etag", - "force", - "requestId", - "validateOnly", - ) - ) - & set(("name",)) - ) + unset_fields = transport.promote_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_cluster_rest_interceptors(null_interceptor): +def test_promote_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11071,13 +11779,13 @@ def test_delete_cluster_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_delete_cluster" + transports.AlloyDBAdminRestInterceptor, "post_promote_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_delete_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_promote_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.DeleteClusterRequest.pb(service.DeleteClusterRequest()) + pb_message = service.PromoteClusterRequest.pb(service.PromoteClusterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -11092,7 +11800,7 @@ def test_delete_cluster_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.DeleteClusterRequest() + request = service.PromoteClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -11100,7 +11808,7 @@ def test_delete_cluster_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.delete_cluster( + client.promote_cluster( request, metadata=[ ("key", "val"), @@ -11112,8 +11820,8 @@ def test_delete_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_cluster_rest_bad_request( - transport: str = "rest", request_type=service.DeleteClusterRequest +def test_promote_cluster_rest_bad_request( + transport: str = "rest", request_type=service.PromoteClusterRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11133,10 +11841,10 @@ def test_delete_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_cluster(request) + client.promote_cluster(request) -def test_delete_cluster_rest_flattened(): +def test_promote_cluster_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -11163,20 +11871,20 @@ def test_delete_cluster_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_cluster(**mock_args) + client.promote_cluster(**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/*/clusters/*}" + "%s/v1beta/{name=projects/*/locations/*/clusters/*}:promote" % client.transport._host, args[1], ) -def test_delete_cluster_rest_flattened_error(transport: str = "rest"): +def test_promote_cluster_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11185,13 +11893,13 @@ def test_delete_cluster_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_cluster( - service.DeleteClusterRequest(), + client.promote_cluster( + service.PromoteClusterRequest(), name="name_value", ) -def test_delete_cluster_rest_error(): +def test_promote_cluster_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -11200,18 +11908,18 @@ def test_delete_cluster_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.PromoteClusterRequest, + service.RestoreClusterRequest, dict, ], ) -def test_promote_cluster_rest(request_type): +def test_restore_cluster_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/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. @@ -11226,19 +11934,20 @@ def test_promote_cluster_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.promote_cluster(request) + response = client.restore_cluster(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_promote_cluster_rest_required_fields( - request_type=service.PromoteClusterRequest, +def test_restore_cluster_rest_required_fields( + request_type=service.RestoreClusterRequest, ): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["cluster_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -11249,21 +11958,24 @@ def test_promote_cluster_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).promote_cluster._get_unset_required_fields(jsonified_request) + ).restore_cluster._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" + jsonified_request["clusterId"] = "cluster_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).promote_cluster._get_unset_required_fields(jsonified_request) + ).restore_cluster._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" + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == "cluster_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11297,24 +12009,33 @@ def test_promote_cluster_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.promote_cluster(request) + response = client.restore_cluster(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_promote_cluster_rest_unset_required_fields(): +def test_restore_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.promote_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.restore_cluster._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "clusterId", + "cluster", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_promote_cluster_rest_interceptors(null_interceptor): +def test_restore_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11329,13 +12050,13 @@ def test_promote_cluster_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_promote_cluster" + transports.AlloyDBAdminRestInterceptor, "post_restore_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_promote_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_restore_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.PromoteClusterRequest.pb(service.PromoteClusterRequest()) + pb_message = service.RestoreClusterRequest.pb(service.RestoreClusterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -11350,7 +12071,7 @@ def test_promote_cluster_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.PromoteClusterRequest() + request = service.RestoreClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -11358,7 +12079,7 @@ def test_promote_cluster_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.promote_cluster( + client.restore_cluster( request, metadata=[ ("key", "val"), @@ -11370,8 +12091,8 @@ def test_promote_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_promote_cluster_rest_bad_request( - transport: str = "rest", request_type=service.PromoteClusterRequest +def test_restore_cluster_rest_bad_request( + transport: str = "rest", request_type=service.RestoreClusterRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11379,7 +12100,7 @@ def test_promote_cluster_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/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. @@ -11391,65 +12112,10 @@ def test_promote_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.promote_cluster(request) - - -def test_promote_cluster_rest_flattened(): - client = AlloyDBAdminClient( - 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/clusters/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.promote_cluster(**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/*/clusters/*}:promote" - % client.transport._host, - args[1], - ) - - -def test_promote_cluster_rest_flattened_error(transport: str = "rest"): - client = AlloyDBAdminClient( - 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.promote_cluster( - service.PromoteClusterRequest(), - name="name_value", - ) + client.restore_cluster(request) -def test_promote_cluster_rest_error(): +def test_restore_cluster_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -11458,18 +12124,157 @@ def test_promote_cluster_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.RestoreClusterRequest, + service.CreateSecondaryClusterRequest, dict, ], ) -def test_restore_cluster_rest(request_type): +def test_create_secondary_cluster_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["cluster"] = { + "backup_source": { + "backup_uid": "backup_uid_value", + "backup_name": "backup_name_value", + }, + "migration_source": { + "host_port": "host_port_value", + "reference_id": "reference_id_value", + "source_type": 1, + }, + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "cluster_type": 1, + "database_version": 1, + "network_config": { + "network": "network_value", + "allocated_ip_range": "allocated_ip_range_value", + }, + "network": "network_value", + "etag": "etag_value", + "annotations": {}, + "reconciling": True, + "initial_user": {"user": "user_value", "password": "password_value"}, + "automated_backup_policy": { + "weekly_schedule": { + "start_times": [ + {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} + ], + "days_of_week": [1], + }, + "time_based_retention": { + "retention_period": {"seconds": 751, "nanos": 543} + }, + "quantity_based_retention": {"count": 553}, + "enabled": True, + "backup_window": {}, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "location": "location_value", + "labels": {}, + }, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + "encryption_config": {}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "continuous_backup_config": { + "enabled": True, + "recovery_window_days": 2166, + "encryption_config": {}, + }, + "continuous_backup_info": { + "encryption_info": {}, + "enabled_time": {}, + "schedule": [1], + "earliest_restorable_time": {}, + }, + "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, + "primary_config": { + "secondary_cluster_names": [ + "secondary_cluster_names_value1", + "secondary_cluster_names_value2", + ] + }, + "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 = service.CreateSecondaryClusterRequest.meta.fields["cluster"] + + 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["cluster"].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["cluster"][field])): + del request_init["cluster"][field][i][subfield] + else: + del request_init["cluster"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -11484,14 +12289,14 @@ def test_restore_cluster_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.restore_cluster(request) + response = client.create_secondary_cluster(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_restore_cluster_rest_required_fields( - request_type=service.RestoreClusterRequest, +def test_create_secondary_cluster_rest_required_fields( + request_type=service.CreateSecondaryClusterRequest, ): transport_class = transports.AlloyDBAdminRestTransport @@ -11505,20 +12310,31 @@ def test_restore_cluster_rest_required_fields( ) # verify fields with default values are dropped + assert "clusterId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).restore_cluster._get_unset_required_fields(jsonified_request) + ).create_secondary_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == request_init["cluster_id"] jsonified_request["parent"] = "parent_value" jsonified_request["clusterId"] = "cluster_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).restore_cluster._get_unset_required_fields(jsonified_request) + ).create_secondary_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "cluster_id", + "request_id", + "validate_only", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -11559,21 +12375,33 @@ def test_restore_cluster_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.restore_cluster(request) + response = client.create_secondary_cluster(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "clusterId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_restore_cluster_rest_unset_required_fields(): +def test_create_secondary_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.restore_cluster._get_unset_required_fields({}) + unset_fields = transport.create_secondary_cluster._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) + set( + ( + "clusterId", + "requestId", + "validateOnly", + ) + ) & set( ( "parent", @@ -11585,7 +12413,7 @@ def test_restore_cluster_rest_unset_required_fields(): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_restore_cluster_rest_interceptors(null_interceptor): +def test_create_secondary_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11600,13 +12428,15 @@ def test_restore_cluster_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_restore_cluster" + transports.AlloyDBAdminRestInterceptor, "post_create_secondary_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_restore_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.RestoreClusterRequest.pb(service.RestoreClusterRequest()) + pb_message = service.CreateSecondaryClusterRequest.pb( + service.CreateSecondaryClusterRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -11621,7 +12451,7 @@ def test_restore_cluster_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.RestoreClusterRequest() + request = service.CreateSecondaryClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -11629,7 +12459,7 @@ def test_restore_cluster_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.restore_cluster( + client.create_secondary_cluster( request, metadata=[ ("key", "val"), @@ -11641,8 +12471,8 @@ def test_restore_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_restore_cluster_rest_bad_request( - transport: str = "rest", request_type=service.RestoreClusterRequest +def test_create_secondary_cluster_rest_bad_request( + transport: str = "rest", request_type=service.CreateSecondaryClusterRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11662,196 +12492,125 @@ def test_restore_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.restore_cluster(request) - - -def test_restore_cluster_rest_error(): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.create_secondary_cluster(request) -@pytest.mark.parametrize( - "request_type", - [ - service.CreateSecondaryClusterRequest, - dict, - ], -) -def test_create_secondary_cluster_rest(request_type): +def test_create_secondary_cluster_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["cluster"] = { - "backup_source": { - "backup_uid": "backup_uid_value", - "backup_name": "backup_name_value", - }, - "migration_source": { - "host_port": "host_port_value", - "reference_id": "reference_id_value", - "source_type": 1, - }, - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "cluster_type": 1, - "database_version": 1, - "network_config": { - "network": "network_value", - "allocated_ip_range": "allocated_ip_range_value", - }, - "network": "network_value", - "etag": "etag_value", - "annotations": {}, - "reconciling": True, - "initial_user": {"user": "user_value", "password": "password_value"}, - "automated_backup_policy": { - "weekly_schedule": { - "start_times": [ - {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} - ], - "days_of_week": [1], - }, - "time_based_retention": { - "retention_period": {"seconds": 751, "nanos": 543} - }, - "quantity_based_retention": {"count": 553}, - "enabled": True, - "backup_window": {}, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "location": "location_value", - "labels": {}, - }, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - "encryption_config": {}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "continuous_backup_config": { - "enabled": True, - "recovery_window_days": 2166, - "encryption_config": {}, - }, - "continuous_backup_info": { - "encryption_info": {}, - "enabled_time": {}, - "schedule": [1], - "earliest_restorable_time": {}, - }, - "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, - "primary_config": { - "secondary_cluster_names": [ - "secondary_cluster_names_value1", - "secondary_cluster_names_value2", - ] - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Mock the http request call within the method and 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") - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateSecondaryClusterRequest.meta.fields["cluster"] + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} - 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 = [] + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + cluster_id="cluster_id_value", + ) + mock_args.update(sample_request) - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + # 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 - 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 + client.create_secondary_cluster(**mock_args) - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + # 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/*}/clusters:createsecondary" + % client.transport._host, + args[1], + ) - 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["cluster"].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 +def test_create_secondary_cluster_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + 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_secondary_cluster( + service.CreateSecondaryClusterRequest(), + parent="parent_value", + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + cluster_id="cluster_id_value", + ) + + +def test_create_secondary_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + - 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, - } - ) +@pytest.mark.parametrize( + "request_type", + [ + service.ListInstancesRequest, + dict, + ], +) +def test_list_instances_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # 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["cluster"][field])): - del request_init["cluster"][field][i][subfield] - else: - del request_init["cluster"][field][subfield] + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/clusters/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") + return_value = service.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = service.ListInstancesResponse.pb(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.create_secondary_cluster(request) + response = client.list_instances(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_create_secondary_cluster_rest_required_fields( - request_type=service.CreateSecondaryClusterRequest, -): +def test_list_instances_rest_required_fields(request_type=service.ListInstancesRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} request_init["parent"] = "" - request_init["cluster_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -11859,29 +12618,26 @@ def test_create_secondary_cluster_rest_required_fields( ) # verify fields with default values are dropped - assert "clusterId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_secondary_cluster._get_unset_required_fields(jsonified_request) + ).list_instances._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == request_init["cluster_id"] jsonified_request["parent"] = "parent_value" - jsonified_request["clusterId"] = "cluster_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_secondary_cluster._get_unset_required_fields(jsonified_request) + ).list_instances._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "cluster_id", - "request_id", - "validate_only", + "filter", + "order_by", + "page_size", + "page_token", ) ) jsonified_request.update(unset_fields) @@ -11889,8 +12645,6 @@ def test_create_secondary_cluster_rest_required_fields( # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == "cluster_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11899,7 +12653,7 @@ def test_create_secondary_cluster_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 = service.ListInstancesResponse() # 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 @@ -11911,58 +12665,49 @@ def test_create_secondary_cluster_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 = service.ListInstancesResponse.pb(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.create_secondary_cluster(request) + response = client.list_instances(request) - expected_params = [ - ( - "clusterId", - "", - ), - ("$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_create_secondary_cluster_rest_unset_required_fields(): +def test_list_instances_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_secondary_cluster._get_unset_required_fields({}) + unset_fields = transport.list_instances._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "clusterId", - "requestId", - "validateOnly", - ) - ) - & set( - ( - "parent", - "clusterId", - "cluster", + "filter", + "orderBy", + "pageSize", + "pageToken", ) ) + & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_secondary_cluster_rest_interceptors(null_interceptor): +def test_list_instances_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11975,17 +12720,13 @@ def test_create_secondary_cluster_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_create_secondary_cluster" + transports.AlloyDBAdminRestInterceptor, "post_list_instances" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_list_instances" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.CreateSecondaryClusterRequest.pb( - service.CreateSecondaryClusterRequest() - ) + pb_message = service.ListInstancesRequest.pb(service.ListInstancesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -11996,19 +12737,19 @@ def test_create_secondary_cluster_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = service.ListInstancesResponse.to_json( + service.ListInstancesResponse() ) - request = service.CreateSecondaryClusterRequest() + request = service.ListInstancesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = service.ListInstancesResponse() - client.create_secondary_cluster( + client.list_instances( request, metadata=[ ("key", "val"), @@ -12020,8 +12761,8 @@ def test_create_secondary_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_secondary_cluster_rest_bad_request( - transport: str = "rest", request_type=service.CreateSecondaryClusterRequest +def test_list_instances_rest_bad_request( + transport: str = "rest", request_type=service.ListInstancesRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12029,7 +12770,7 @@ def test_create_secondary_cluster_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -12041,10 +12782,10 @@ def test_create_secondary_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_secondary_cluster(request) + client.list_instances(request) -def test_create_secondary_cluster_rest_flattened(): +def test_list_instances_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -12053,42 +12794,42 @@ def test_create_secondary_cluster_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 = service.ListInstancesResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "parent": "projects/sample1/locations/sample2/clusters/sample3" + } # get truthy value for each flattened field mock_args = dict( parent="parent_value", - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - cluster_id="cluster_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 = service.ListInstancesResponse.pb(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.create_secondary_cluster(**mock_args) + client.list_instances(**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/*}/clusters:createsecondary" + "%s/v1beta/{parent=projects/*/locations/*/clusters/*}/instances" % client.transport._host, args[1], ) -def test_create_secondary_cluster_rest_flattened_error(transport: str = "rest"): +def test_list_instances_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12097,69 +12838,144 @@ def test_create_secondary_cluster_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.create_secondary_cluster( - service.CreateSecondaryClusterRequest(), + client.list_instances( + service.ListInstancesRequest(), parent="parent_value", - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - cluster_id="cluster_id_value", ) -def test_create_secondary_cluster_rest_error(): +def test_list_instances_rest_pager(transport: str = "rest"): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token="abc", + ), + service.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token="ghi", + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListInstancesResponse.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/clusters/sample3" + } + + pager = client.list_instances(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Instance) for i in results) + + pages = list(client.list_instances(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - service.ListInstancesRequest, + service.GetInstanceRequest, dict, ], ) -def test_list_instances_rest(request_type): +def test_get_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/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 = service.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + return_value = resources.Instance( + name="name_value", + display_name="display_name_value", + uid="uid_value", + state=resources.Instance.State.READY, + instance_type=resources.Instance.InstanceType.PRIMARY, + availability_type=resources.Instance.AvailabilityType.ZONAL, + gce_zone="gce_zone_value", + ip_address="ip_address_value", + public_ip_address="public_ip_address_value", + reconciling=True, + etag="etag_value", + satisfies_pzs=True, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListInstancesResponse.pb(return_value) + return_value = resources.Instance.pb(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_instances(request) + response = client.get_instance(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, resources.Instance) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.uid == "uid_value" + assert response.state == resources.Instance.State.READY + assert response.instance_type == resources.Instance.InstanceType.PRIMARY + assert response.availability_type == resources.Instance.AvailabilityType.ZONAL + assert response.gce_zone == "gce_zone_value" + assert response.ip_address == "ip_address_value" + assert response.public_ip_address == "public_ip_address_value" + assert response.reconciling is True + assert response.etag == "etag_value" + assert response.satisfies_pzs is True -def test_list_instances_rest_required_fields(request_type=service.ListInstancesRequest): +def test_get_instance_rest_required_fields(request_type=service.GetInstanceRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -12170,30 +12986,23 @@ def test_list_instances_rest_required_fields(request_type=service.ListInstancesR unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_instances._get_unset_required_fields(jsonified_request) + ).get_instance._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" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_instances._get_unset_required_fields(jsonified_request) + ).get_instance._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", - ) - ) + assert not set(unset_fields) - set(("view",)) 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 "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12202,7 +13011,7 @@ def test_list_instances_rest_required_fields(request_type=service.ListInstancesR request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListInstancesResponse() + return_value = resources.Instance() # 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 @@ -12223,40 +13032,30 @@ def test_list_instances_rest_required_fields(request_type=service.ListInstancesR response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListInstancesResponse.pb(return_value) + return_value = resources.Instance.pb(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_instances(request) + response = client.get_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_instances_rest_unset_required_fields(): +def test_get_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_instances._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.get_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("view",)) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_instances_rest_interceptors(null_interceptor): +def test_get_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12269,13 +13068,13 @@ def test_list_instances_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_list_instances" + transports.AlloyDBAdminRestInterceptor, "post_get_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_list_instances" + transports.AlloyDBAdminRestInterceptor, "pre_get_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListInstancesRequest.pb(service.ListInstancesRequest()) + pb_message = service.GetInstanceRequest.pb(service.GetInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12286,19 +13085,17 @@ def test_list_instances_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = service.ListInstancesResponse.to_json( - service.ListInstancesResponse() - ) + req.return_value._content = resources.Instance.to_json(resources.Instance()) - request = service.ListInstancesRequest() + request = service.GetInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListInstancesResponse() + post.return_value = resources.Instance() - client.list_instances( + client.get_instance( request, metadata=[ ("key", "val"), @@ -12310,8 +13107,8 @@ def test_list_instances_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_instances_rest_bad_request( - transport: str = "rest", request_type=service.ListInstancesRequest +def test_get_instance_rest_bad_request( + transport: str = "rest", request_type=service.GetInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12319,7 +13116,9 @@ def test_list_instances_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -12331,10 +13130,10 @@ def test_list_instances_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_instances(request) + client.get_instance(request) -def test_list_instances_rest_flattened(): +def test_get_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -12343,16 +13142,16 @@ def test_list_instances_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 = service.ListInstancesResponse() + return_value = resources.Instance() # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/clusters/sample3" + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) @@ -12360,25 +13159,25 @@ def test_list_instances_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListInstancesResponse.pb(return_value) + return_value = resources.Instance.pb(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_instances(**mock_args) + client.get_instance(**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/*/clusters/*}/instances" + "%s/v1beta/{name=projects/*/locations/*/clusters/*/instances/*}" % client.transport._host, args[1], ) -def test_list_instances_rest_flattened_error(transport: str = "rest"): +def test_get_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12387,140 +13186,197 @@ def test_list_instances_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.list_instances( - service.ListInstancesRequest(), - parent="parent_value", + client.get_instance( + service.GetInstanceRequest(), + name="name_value", ) -def test_list_instances_rest_pager(transport: str = "rest"): +def test_get_instance_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateInstanceRequest, + dict, + ], +) +def test_create_instance_rest(request_type): client = AlloyDBAdminClient( 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 = ( - service.ListInstancesResponse( - instances=[ - resources.Instance(), - resources.Instance(), - resources.Instance(), - ], - next_page_token="abc", - ), - service.ListInstancesResponse( - instances=[], - next_page_token="def", - ), - service.ListInstancesResponse( - instances=[ - resources.Instance(), - ], - next_page_token="ghi", - ), - service.ListInstancesResponse( - instances=[ - resources.Instance(), - resources.Instance(), - ], - ), - ) - # Two responses for two calls - response = response + response + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init["instance"] = { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "instance_type": 1, + "machine_config": {"cpu_count": 976}, + "availability_type": 1, + "gce_zone": "gce_zone_value", + "database_flags": {}, + "writable_node": { + "zone_id": "zone_id_value", + "id": "id_value", + "ip": "ip_value", + "state": "state_value", + }, + "nodes": {}, + "query_insights_config": { + "record_application_tags": True, + "record_client_address": True, + "query_string_length": 2061, + "query_plans_per_minute": 2378, + }, + "read_pool_config": {"node_count": 1070}, + "ip_address": "ip_address_value", + "public_ip_address": "public_ip_address_value", + "reconciling": True, + "etag": "etag_value", + "annotations": {}, + "update_policy": {"mode": 1}, + "client_connection_config": { + "require_connectors": True, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + }, + "satisfies_pzs": True, + "psc_instance_config": { + "service_attachment_link": "service_attachment_link_value", + "allowed_consumer_projects": [ + "allowed_consumer_projects_value1", + "allowed_consumer_projects_value2", + ], + "allowed_consumer_networks": [ + "allowed_consumer_networks_value1", + "allowed_consumer_networks_value2", + ], + "psc_interface_configs": [ + { + "consumer_endpoint_ips": [ + "consumer_endpoint_ips_value1", + "consumer_endpoint_ips_value2", + ], + "network_attachment": "network_attachment_value", + } + ], + "outgoing_service_attachment_links": [ + "outgoing_service_attachment_links_value1", + "outgoing_service_attachment_links_value2", + ], + "psc_enabled": True, + }, + "network_config": { + "authorized_external_networks": [{"cidr_range": "cidr_range_value"}], + "enable_public_ip": 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 - # Wrap the values into proper Response objs - response = tuple(service.ListInstancesResponse.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 + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateInstanceRequest.meta.fields["instance"] - sample_request = { - "parent": "projects/sample1/locations/sample2/clusters/sample3" - } + 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 = [] - pager = client.list_instances(request=sample_request) + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Instance) for i in results) + 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 - pages = list(client.list_instances(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + 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 = [] -@pytest.mark.parametrize( - "request_type", - [ - service.GetInstanceRequest, - dict, - ], -) -def test_get_instance_rest(request_type): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # 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["instance"].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 - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + 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["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][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 = resources.Instance( - name="name_value", - display_name="display_name_value", - uid="uid_value", - state=resources.Instance.State.READY, - instance_type=resources.Instance.InstanceType.PRIMARY, - availability_type=resources.Instance.AvailabilityType.ZONAL, - gce_zone="gce_zone_value", - ip_address="ip_address_value", - reconciling=True, - etag="etag_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Instance.pb(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_instance(request) + response = client.create_instance(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Instance) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.uid == "uid_value" - assert response.state == resources.Instance.State.READY - assert response.instance_type == resources.Instance.InstanceType.PRIMARY - assert response.availability_type == resources.Instance.AvailabilityType.ZONAL - assert response.gce_zone == "gce_zone_value" - assert response.ip_address == "ip_address_value" - assert response.reconciling is True - assert response.etag == "etag_value" + assert response.operation.name == "operations/spam" -def test_get_instance_rest_required_fields(request_type=service.GetInstanceRequest): +def test_create_instance_rest_required_fields( + request_type=service.CreateInstanceRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["instance_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -12528,26 +13384,38 @@ def test_get_instance_rest_required_fields(request_type=service.GetInstanceReque ) # verify fields with default values are dropped + assert "instanceId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_instance._get_unset_required_fields(jsonified_request) + ).create_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["instanceId"] = "instance_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_instance._get_unset_required_fields(jsonified_request) + ).create_instance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("view",)) + assert not set(unset_fields) - set( + ( + "instance_id", + "request_id", + "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 "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == "instance_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12556,7 +13424,7 @@ def test_get_instance_rest_required_fields(request_type=service.GetInstanceReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Instance() + 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 @@ -12568,39 +13436,58 @@ def test_get_instance_rest_required_fields(request_type=service.GetInstanceReque 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 = resources.Instance.pb(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_instance(request) + response = client.create_instance(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "instanceId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_instance_rest_unset_required_fields(): +def test_create_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(("view",)) & set(("name",))) + unset_fields = transport.create_instance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "instanceId", + "requestId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "instanceId", + "instance", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_instance_rest_interceptors(null_interceptor): +def test_create_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12613,13 +13500,15 @@ def test_get_instance_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_get_instance" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_create_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_get_instance" + transports.AlloyDBAdminRestInterceptor, "pre_create_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.GetInstanceRequest.pb(service.GetInstanceRequest()) + pb_message = service.CreateInstanceRequest.pb(service.CreateInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12630,17 +13519,19 @@ def test_get_instance_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.Instance.to_json(resources.Instance()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) - request = service.GetInstanceRequest() + request = service.CreateInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Instance() + post.return_value = operations_pb2.Operation() - client.get_instance( + client.create_instance( request, metadata=[ ("key", "val"), @@ -12652,8 +13543,8 @@ def test_get_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_instance_rest_bad_request( - transport: str = "rest", request_type=service.GetInstanceRequest +def test_create_instance_rest_bad_request( + transport: str = "rest", request_type=service.CreateInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12661,9 +13552,7 @@ def test_get_instance_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -12675,10 +13564,10 @@ def test_get_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_instance(request) + client.create_instance(request) -def test_get_instance_rest_flattened(): +def test_create_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -12687,42 +13576,42 @@ def test_get_instance_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 = resources.Instance() + 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/clusters/sample3/instances/sample4" + "parent": "projects/sample1/locations/sample2/clusters/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_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 = resources.Instance.pb(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_instance(**mock_args) + client.create_instance(**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/*/clusters/*/instances/*}" + "%s/v1beta/{parent=projects/*/locations/*/clusters/*}/instances" % client.transport._host, args[1], ) -def test_get_instance_rest_flattened_error(transport: str = "rest"): +def test_create_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12731,13 +13620,15 @@ def test_get_instance_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.get_instance( - service.GetInstanceRequest(), - name="name_value", + client.create_instance( + service.CreateInstanceRequest(), + parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_id_value", ) -def test_get_instance_rest_error(): +def test_create_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -12746,11 +13637,11 @@ def test_get_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.CreateInstanceRequest, + service.CreateSecondaryInstanceRequest, dict, ], ) -def test_create_instance_rest(request_type): +def test_create_secondary_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -12787,6 +13678,7 @@ def test_create_instance_rest(request_type): }, "read_pool_config": {"node_count": 1070}, "ip_address": "ip_address_value", + "public_ip_address": "public_ip_address_value", "reconciling": True, "etag": "etag_value", "annotations": {}, @@ -12795,13 +13687,43 @@ def test_create_instance_rest(request_type): "require_connectors": True, "ssl_config": {"ssl_mode": 1, "ca_source": 1}, }, + "satisfies_pzs": True, + "psc_instance_config": { + "service_attachment_link": "service_attachment_link_value", + "allowed_consumer_projects": [ + "allowed_consumer_projects_value1", + "allowed_consumer_projects_value2", + ], + "allowed_consumer_networks": [ + "allowed_consumer_networks_value1", + "allowed_consumer_networks_value2", + ], + "psc_interface_configs": [ + { + "consumer_endpoint_ips": [ + "consumer_endpoint_ips_value1", + "consumer_endpoint_ips_value2", + ], + "network_attachment": "network_attachment_value", + } + ], + "outgoing_service_attachment_links": [ + "outgoing_service_attachment_links_value1", + "outgoing_service_attachment_links_value2", + ], + "psc_enabled": True, + }, + "network_config": { + "authorized_external_networks": [{"cidr_range": "cidr_range_value"}], + "enable_public_ip": 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 = service.CreateInstanceRequest.meta.fields["instance"] + test_field = service.CreateSecondaryInstanceRequest.meta.fields["instance"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -12877,14 +13799,14 @@ def get_message_fields(field): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_instance(request) + response = client.create_secondary_instance(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_create_instance_rest_required_fields( - request_type=service.CreateInstanceRequest, +def test_create_secondary_instance_rest_required_fields( + request_type=service.CreateSecondaryInstanceRequest, ): transport_class = transports.AlloyDBAdminRestTransport @@ -12902,7 +13824,7 @@ def test_create_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_instance._get_unset_required_fields(jsonified_request) + ).create_secondary_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -12914,7 +13836,7 @@ def test_create_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_instance._get_unset_required_fields(jsonified_request) + ).create_secondary_instance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( @@ -12963,7 +13885,7 @@ def test_create_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_instance(request) + response = client.create_secondary_instance(request) expected_params = [ ( @@ -12976,12 +13898,12 @@ def test_create_instance_rest_required_fields( assert expected_params == actual_params -def test_create_instance_rest_unset_required_fields(): +def test_create_secondary_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_instance._get_unset_required_fields({}) + unset_fields = transport.create_secondary_instance._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( @@ -13001,7 +13923,7 @@ def test_create_instance_rest_unset_required_fields(): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_instance_rest_interceptors(null_interceptor): +def test_create_secondary_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13016,13 +13938,15 @@ def test_create_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_create_instance" + transports.AlloyDBAdminRestInterceptor, "post_create_secondary_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_create_instance" + transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.CreateInstanceRequest.pb(service.CreateInstanceRequest()) + pb_message = service.CreateSecondaryInstanceRequest.pb( + service.CreateSecondaryInstanceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13037,7 +13961,7 @@ def test_create_instance_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.CreateInstanceRequest() + request = service.CreateSecondaryInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -13045,7 +13969,7 @@ def test_create_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_instance( + client.create_secondary_instance( request, metadata=[ ("key", "val"), @@ -13057,8 +13981,8 @@ def test_create_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_instance_rest_bad_request( - transport: str = "rest", request_type=service.CreateInstanceRequest +def test_create_secondary_instance_rest_bad_request( + transport: str = "rest", request_type=service.CreateSecondaryInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13078,10 +14002,10 @@ def test_create_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_instance(request) + client.create_secondary_instance(request) -def test_create_instance_rest_flattened(): +def test_create_secondary_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13112,20 +14036,20 @@ def test_create_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_instance(**mock_args) + client.create_secondary_instance(**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/*/clusters/*}/instances" + "%s/v1beta/{parent=projects/*/locations/*/clusters/*}/instances:createsecondary" % client.transport._host, args[1], ) -def test_create_instance_rest_flattened_error(transport: str = "rest"): +def test_create_secondary_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13134,15 +14058,15 @@ def test_create_instance_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.create_instance( - service.CreateInstanceRequest(), + client.create_secondary_instance( + service.CreateSecondaryInstanceRequest(), parent="parent_value", instance=resources.Instance(name="name_value"), instance_id="instance_id_value", ) -def test_create_instance_rest_error(): +def test_create_secondary_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -13151,11 +14075,11 @@ def test_create_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.CreateSecondaryInstanceRequest, + service.BatchCreateInstancesRequest, dict, ], ) -def test_create_secondary_instance_rest(request_type): +def test_batch_create_instances_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13163,50 +14087,93 @@ def test_create_secondary_instance_rest(request_type): # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} - request_init["instance"] = { - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "instance_type": 1, - "machine_config": {"cpu_count": 976}, - "availability_type": 1, - "gce_zone": "gce_zone_value", - "database_flags": {}, - "writable_node": { - "zone_id": "zone_id_value", - "id": "id_value", - "ip": "ip_value", - "state": "state_value", - }, - "nodes": {}, - "query_insights_config": { - "record_application_tags": True, - "record_client_address": True, - "query_string_length": 2061, - "query_plans_per_minute": 2378, - }, - "read_pool_config": {"node_count": 1070}, - "ip_address": "ip_address_value", - "reconciling": True, - "etag": "etag_value", - "annotations": {}, - "update_policy": {"mode": 1}, - "client_connection_config": { - "require_connectors": True, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - }, + request_init["requests"] = { + "create_instance_requests": [ + { + "parent": "parent_value", + "instance_id": "instance_id_value", + "instance": { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "instance_type": 1, + "machine_config": {"cpu_count": 976}, + "availability_type": 1, + "gce_zone": "gce_zone_value", + "database_flags": {}, + "writable_node": { + "zone_id": "zone_id_value", + "id": "id_value", + "ip": "ip_value", + "state": "state_value", + }, + "nodes": {}, + "query_insights_config": { + "record_application_tags": True, + "record_client_address": True, + "query_string_length": 2061, + "query_plans_per_minute": 2378, + }, + "read_pool_config": {"node_count": 1070}, + "ip_address": "ip_address_value", + "public_ip_address": "public_ip_address_value", + "reconciling": True, + "etag": "etag_value", + "annotations": {}, + "update_policy": {"mode": 1}, + "client_connection_config": { + "require_connectors": True, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + }, + "satisfies_pzs": True, + "psc_instance_config": { + "service_attachment_link": "service_attachment_link_value", + "allowed_consumer_projects": [ + "allowed_consumer_projects_value1", + "allowed_consumer_projects_value2", + ], + "allowed_consumer_networks": [ + "allowed_consumer_networks_value1", + "allowed_consumer_networks_value2", + ], + "psc_interface_configs": [ + { + "consumer_endpoint_ips": [ + "consumer_endpoint_ips_value1", + "consumer_endpoint_ips_value2", + ], + "network_attachment": "network_attachment_value", + } + ], + "outgoing_service_attachment_links": [ + "outgoing_service_attachment_links_value1", + "outgoing_service_attachment_links_value2", + ], + "psc_enabled": True, + }, + "network_config": { + "authorized_external_networks": [ + {"cidr_range": "cidr_range_value"} + ], + "enable_public_ip": True, + }, + }, + "request_id": "request_id_value", + "validate_only": 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 = service.CreateSecondaryInstanceRequest.meta.fields["instance"] + test_field = service.BatchCreateInstancesRequest.meta.fields["requests"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -13234,7 +14201,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["instance"].items(): # pragma: NO COVER + for field, value in request_init["requests"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -13264,10 +14231,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["instance"][field])): - del request_init["instance"][field][i][subfield] + for i in range(0, len(request_init["requests"][field])): + del request_init["requests"][field][i][subfield] else: - del request_init["instance"][field][subfield] + del request_init["requests"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -13282,20 +14249,19 @@ def get_message_fields(field): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_secondary_instance(request) + response = client.batch_create_instances(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_create_secondary_instance_rest_required_fields( - request_type=service.CreateSecondaryInstanceRequest, +def test_batch_create_instances_rest_required_fields( + request_type=service.BatchCreateInstancesRequest, ): transport_class = transports.AlloyDBAdminRestTransport request_init = {} request_init["parent"] = "" - request_init["instance_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -13303,38 +14269,26 @@ def test_create_secondary_instance_rest_required_fields( ) # verify fields with default values are dropped - assert "instanceId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_secondary_instance._get_unset_required_fields(jsonified_request) + ).batch_create_instances._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == request_init["instance_id"] jsonified_request["parent"] = "parent_value" - jsonified_request["instanceId"] = "instance_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_secondary_instance._get_unset_required_fields(jsonified_request) + ).batch_create_instances._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "instance_id", - "request_id", - "validate_only", - ) - ) + assert not set(unset_fields) - set(("request_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 "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == "instance_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13368,45 +14322,32 @@ def test_create_secondary_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_secondary_instance(request) + response = client.batch_create_instances(request) - expected_params = [ - ( - "instanceId", - "", - ), - ("$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_create_secondary_instance_rest_unset_required_fields(): +def test_batch_create_instances_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_secondary_instance._get_unset_required_fields({}) + unset_fields = transport.batch_create_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "instanceId", - "requestId", - "validateOnly", - ) - ) + set(("requestId",)) & set( ( "parent", - "instanceId", - "instance", + "requests", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_secondary_instance_rest_interceptors(null_interceptor): +def test_batch_create_instances_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13421,14 +14362,14 @@ def test_create_secondary_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_create_secondary_instance" + transports.AlloyDBAdminRestInterceptor, "post_batch_create_instances" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_instance" + transports.AlloyDBAdminRestInterceptor, "pre_batch_create_instances" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.CreateSecondaryInstanceRequest.pb( - service.CreateSecondaryInstanceRequest() + pb_message = service.BatchCreateInstancesRequest.pb( + service.BatchCreateInstancesRequest() ) transcode.return_value = { "method": "post", @@ -13444,7 +14385,7 @@ def test_create_secondary_instance_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.CreateSecondaryInstanceRequest() + request = service.BatchCreateInstancesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -13452,7 +14393,7 @@ def test_create_secondary_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_secondary_instance( + client.batch_create_instances( request, metadata=[ ("key", "val"), @@ -13464,8 +14405,8 @@ def test_create_secondary_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_secondary_instance_rest_bad_request( - transport: str = "rest", request_type=service.CreateSecondaryInstanceRequest +def test_batch_create_instances_rest_bad_request( + transport: str = "rest", request_type=service.BatchCreateInstancesRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13476,80 +14417,19 @@ def test_create_secondary_instance_rest_bad_request( request_init = {"parent": "projects/sample1/locations/sample2/clusters/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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_secondary_instance(request) - - -def test_create_secondary_instance_rest_flattened(): - client = AlloyDBAdminClient( - 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/clusters/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - instance=resources.Instance(name="name_value"), - instance_id="instance_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_secondary_instance(**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/*/clusters/*}/instances:createsecondary" - % client.transport._host, - args[1], - ) - - -def test_create_secondary_instance_rest_flattened_error(transport: str = "rest"): - client = AlloyDBAdminClient( - 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_secondary_instance( - service.CreateSecondaryInstanceRequest(), - parent="parent_value", - instance=resources.Instance(name="name_value"), - instance_id="instance_id_value", - ) + # 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_create_instances(request) -def test_create_secondary_instance_rest_error(): +def test_batch_create_instances_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -13558,72 +14438,97 @@ def test_create_secondary_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.BatchCreateInstancesRequest, + service.UpdateInstanceRequest, dict, ], ) -def test_batch_create_instances_rest(request_type): +def test_update_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} - request_init["requests"] = { - "create_instance_requests": [ - { - "parent": "parent_value", - "instance_id": "instance_id_value", - "instance": { - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "instance_type": 1, - "machine_config": {"cpu_count": 976}, - "availability_type": 1, - "gce_zone": "gce_zone_value", - "database_flags": {}, - "writable_node": { - "zone_id": "zone_id_value", - "id": "id_value", - "ip": "ip_value", - "state": "state_value", - }, - "nodes": {}, - "query_insights_config": { - "record_application_tags": True, - "record_client_address": True, - "query_string_length": 2061, - "query_plans_per_minute": 2378, - }, - "read_pool_config": {"node_count": 1070}, - "ip_address": "ip_address_value", - "reconciling": True, - "etag": "etag_value", - "annotations": {}, - "update_policy": {"mode": 1}, - "client_connection_config": { - "require_connectors": True, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - }, - }, - "request_id": "request_id_value", - "validate_only": True, - } - ] + request_init = { + "instance": { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } + } + request_init["instance"] = { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "instance_type": 1, + "machine_config": {"cpu_count": 976}, + "availability_type": 1, + "gce_zone": "gce_zone_value", + "database_flags": {}, + "writable_node": { + "zone_id": "zone_id_value", + "id": "id_value", + "ip": "ip_value", + "state": "state_value", + }, + "nodes": {}, + "query_insights_config": { + "record_application_tags": True, + "record_client_address": True, + "query_string_length": 2061, + "query_plans_per_minute": 2378, + }, + "read_pool_config": {"node_count": 1070}, + "ip_address": "ip_address_value", + "public_ip_address": "public_ip_address_value", + "reconciling": True, + "etag": "etag_value", + "annotations": {}, + "update_policy": {"mode": 1}, + "client_connection_config": { + "require_connectors": True, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + }, + "satisfies_pzs": True, + "psc_instance_config": { + "service_attachment_link": "service_attachment_link_value", + "allowed_consumer_projects": [ + "allowed_consumer_projects_value1", + "allowed_consumer_projects_value2", + ], + "allowed_consumer_networks": [ + "allowed_consumer_networks_value1", + "allowed_consumer_networks_value2", + ], + "psc_interface_configs": [ + { + "consumer_endpoint_ips": [ + "consumer_endpoint_ips_value1", + "consumer_endpoint_ips_value2", + ], + "network_attachment": "network_attachment_value", + } + ], + "outgoing_service_attachment_links": [ + "outgoing_service_attachment_links_value1", + "outgoing_service_attachment_links_value2", + ], + "psc_enabled": True, + }, + "network_config": { + "authorized_external_networks": [{"cidr_range": "cidr_range_value"}], + "enable_public_ip": 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 = service.BatchCreateInstancesRequest.meta.fields["requests"] + test_field = service.UpdateInstanceRequest.meta.fields["instance"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -13651,7 +14556,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["requests"].items(): # pragma: NO COVER + for field, value in request_init["instance"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -13681,10 +14586,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["requests"][field])): - del request_init["requests"][field][i][subfield] + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] else: - del request_init["requests"][field][subfield] + del request_init["instance"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -13699,19 +14604,18 @@ def get_message_fields(field): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_create_instances(request) + response = client.update_instance(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_batch_create_instances_rest_required_fields( - request_type=service.BatchCreateInstancesRequest, +def test_update_instance_rest_required_fields( + request_type=service.UpdateInstanceRequest, ): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -13722,23 +14626,26 @@ def test_batch_create_instances_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_create_instances._get_unset_required_fields(jsonified_request) + ).update_instance._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_instances._get_unset_required_fields(jsonified_request) + ).update_instance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "allow_missing", + "request_id", + "update_mask", + "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" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13759,7 +14666,7 @@ def test_batch_create_instances_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 @@ -13772,32 +14679,34 @@ def test_batch_create_instances_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_create_instances(request) + response = client.update_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_batch_create_instances_rest_unset_required_fields(): +def test_update_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.batch_create_instances._get_unset_required_fields({}) + unset_fields = transport.update_instance._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) - & set( + set( ( - "parent", - "requests", + "allowMissing", + "requestId", + "updateMask", + "validateOnly", ) ) + & set(("instance",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_instances_rest_interceptors(null_interceptor): +def test_update_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13812,15 +14721,13 @@ def test_batch_create_instances_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_batch_create_instances" + transports.AlloyDBAdminRestInterceptor, "post_update_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_batch_create_instances" + transports.AlloyDBAdminRestInterceptor, "pre_update_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.BatchCreateInstancesRequest.pb( - service.BatchCreateInstancesRequest() - ) + pb_message = service.UpdateInstanceRequest.pb(service.UpdateInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13835,7 +14742,7 @@ def test_batch_create_instances_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.BatchCreateInstancesRequest() + request = service.UpdateInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -13843,7 +14750,7 @@ def test_batch_create_instances_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.batch_create_instances( + client.update_instance( request, metadata=[ ("key", "val"), @@ -13855,8 +14762,8 @@ def test_batch_create_instances_rest_interceptors(null_interceptor): post.assert_called_once() -def test_batch_create_instances_rest_bad_request( - transport: str = "rest", request_type=service.BatchCreateInstancesRequest +def test_update_instance_rest_bad_request( + transport: str = "rest", request_type=service.UpdateInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13864,7 +14771,11 @@ def test_batch_create_instances_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = { + "instance": { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -13876,10 +14787,71 @@ def test_batch_create_instances_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.batch_create_instances(request) + client.update_instance(request) -def test_batch_create_instances_rest_error(): +def test_update_instance_rest_flattened(): + client = AlloyDBAdminClient( + 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 = { + "instance": { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + instance=resources.Instance(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_instance(**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/{instance.name=projects/*/locations/*/clusters/*/instances/*}" + % client.transport._host, + args[1], + ) + + +def test_update_instance_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + 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_instance( + service.UpdateInstanceRequest(), + instance=resources.Instance(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -13888,11 +14860,11 @@ def test_batch_create_instances_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.UpdateInstanceRequest, + service.DeleteInstanceRequest, dict, ], ) -def test_update_instance_rest(request_type): +def test_delete_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13900,115 +14872,8 @@ def test_update_instance_rest(request_type): # send a request that will satisfy transcoding request_init = { - "instance": { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } - } - request_init["instance"] = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "instance_type": 1, - "machine_config": {"cpu_count": 976}, - "availability_type": 1, - "gce_zone": "gce_zone_value", - "database_flags": {}, - "writable_node": { - "zone_id": "zone_id_value", - "id": "id_value", - "ip": "ip_value", - "state": "state_value", - }, - "nodes": {}, - "query_insights_config": { - "record_application_tags": True, - "record_client_address": True, - "query_string_length": 2061, - "query_plans_per_minute": 2378, - }, - "read_pool_config": {"node_count": 1070}, - "ip_address": "ip_address_value", - "reconciling": True, - "etag": "etag_value", - "annotations": {}, - "update_policy": {"mode": 1}, - "client_connection_config": { - "require_connectors": True, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - }, + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } - # 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 = service.UpdateInstanceRequest.meta.fields["instance"] - - 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["instance"].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["instance"][field])): - del request_init["instance"][field][i][subfield] - else: - del request_init["instance"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -14023,18 +14888,19 @@ def get_message_fields(field): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_instance(request) + response = client.delete_instance(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_update_instance_rest_required_fields( - request_type=service.UpdateInstanceRequest, +def test_delete_instance_rest_required_fields( + request_type=service.DeleteInstanceRequest, ): transport_class = transports.AlloyDBAdminRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14045,26 +14911,29 @@ def test_update_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_instance._get_unset_required_fields(jsonified_request) + ).delete_instance._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_instance._get_unset_required_fields(jsonified_request) + ).delete_instance._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", "request_id", - "update_mask", "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 = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14085,10 +14954,9 @@ def test_update_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -14098,34 +14966,33 @@ def test_update_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_instance(request) + response = client.delete_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_instance_rest_unset_required_fields(): +def test_delete_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_instance._get_unset_required_fields({}) + unset_fields = transport.delete_instance._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "allowMissing", + "etag", "requestId", - "updateMask", "validateOnly", ) ) - & set(("instance",)) + & set(("name",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_instance_rest_interceptors(null_interceptor): +def test_delete_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14140,13 +15007,13 @@ def test_update_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_update_instance" + transports.AlloyDBAdminRestInterceptor, "post_delete_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_update_instance" + transports.AlloyDBAdminRestInterceptor, "pre_delete_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.UpdateInstanceRequest.pb(service.UpdateInstanceRequest()) + pb_message = service.DeleteInstanceRequest.pb(service.DeleteInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14161,7 +15028,7 @@ def test_update_instance_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.UpdateInstanceRequest() + request = service.DeleteInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -14169,7 +15036,7 @@ def test_update_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.update_instance( + client.delete_instance( request, metadata=[ ("key", "val"), @@ -14181,8 +15048,8 @@ def test_update_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_instance_rest_bad_request( - transport: str = "rest", request_type=service.UpdateInstanceRequest +def test_delete_instance_rest_bad_request( + transport: str = "rest", request_type=service.DeleteInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14191,9 +15058,7 @@ def test_update_instance_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "instance": { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } request = request_type(**request_init) @@ -14206,10 +15071,10 @@ def test_update_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_instance(request) + client.delete_instance(request) -def test_update_instance_rest_flattened(): +def test_delete_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14222,15 +15087,12 @@ def test_update_instance_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "instance": { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } # get truthy value for each flattened field mock_args = dict( - instance=resources.Instance(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -14241,20 +15103,20 @@ def test_update_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_instance(**mock_args) + client.delete_instance(**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/{instance.name=projects/*/locations/*/clusters/*/instances/*}" + "%s/v1beta/{name=projects/*/locations/*/clusters/*/instances/*}" % client.transport._host, args[1], ) -def test_update_instance_rest_flattened_error(transport: str = "rest"): +def test_delete_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14263,14 +15125,13 @@ def test_update_instance_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_instance( - service.UpdateInstanceRequest(), - instance=resources.Instance(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_instance( + service.DeleteInstanceRequest(), + name="name_value", ) -def test_update_instance_rest_error(): +def test_delete_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -14279,11 +15140,11 @@ def test_update_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.DeleteInstanceRequest, + service.FailoverInstanceRequest, dict, ], ) -def test_delete_instance_rest(request_type): +def test_failover_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14307,14 +15168,14 @@ def test_delete_instance_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_instance(request) + response = client.failover_instance(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_delete_instance_rest_required_fields( - request_type=service.DeleteInstanceRequest, +def test_failover_instance_rest_required_fields( + request_type=service.FailoverInstanceRequest, ): transport_class = transports.AlloyDBAdminRestTransport @@ -14330,7 +15191,7 @@ def test_delete_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_instance._get_unset_required_fields(jsonified_request) + ).failover_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -14339,15 +15200,7 @@ def test_delete_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_instance._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "etag", - "request_id", - "validate_only", - ) - ) + ).failover_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -14373,9 +15226,10 @@ def test_delete_instance_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() @@ -14385,33 +15239,24 @@ def test_delete_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_instance(request) + response = client.failover_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_instance_rest_unset_required_fields(): +def test_failover_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_instance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "etag", - "requestId", - "validateOnly", - ) - ) - & set(("name",)) - ) + unset_fields = transport.failover_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_instance_rest_interceptors(null_interceptor): +def test_failover_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14426,13 +15271,15 @@ def test_delete_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_delete_instance" + transports.AlloyDBAdminRestInterceptor, "post_failover_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_delete_instance" + transports.AlloyDBAdminRestInterceptor, "pre_failover_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.DeleteInstanceRequest.pb(service.DeleteInstanceRequest()) + pb_message = service.FailoverInstanceRequest.pb( + service.FailoverInstanceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14447,7 +15294,7 @@ def test_delete_instance_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.DeleteInstanceRequest() + request = service.FailoverInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -14455,7 +15302,7 @@ def test_delete_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.delete_instance( + client.failover_instance( request, metadata=[ ("key", "val"), @@ -14467,8 +15314,8 @@ def test_delete_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_instance_rest_bad_request( - transport: str = "rest", request_type=service.DeleteInstanceRequest +def test_failover_instance_rest_bad_request( + transport: str = "rest", request_type=service.FailoverInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14490,10 +15337,10 @@ def test_delete_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_instance(request) + client.failover_instance(request) -def test_delete_instance_rest_flattened(): +def test_failover_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14522,20 +15369,20 @@ def test_delete_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_instance(**mock_args) + client.failover_instance(**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/*/clusters/*/instances/*}" + "%s/v1beta/{name=projects/*/locations/*/clusters/*/instances/*}:failover" % client.transport._host, args[1], ) -def test_delete_instance_rest_flattened_error(transport: str = "rest"): +def test_failover_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14544,13 +15391,13 @@ def test_delete_instance_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_instance( - service.DeleteInstanceRequest(), + client.failover_instance( + service.FailoverInstanceRequest(), name="name_value", ) -def test_delete_instance_rest_error(): +def test_failover_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -14559,11 +15406,11 @@ def test_delete_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.FailoverInstanceRequest, + service.InjectFaultRequest, dict, ], ) -def test_failover_instance_rest(request_type): +def test_inject_fault_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14587,15 +15434,13 @@ def test_failover_instance_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.failover_instance(request) + response = client.inject_fault(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_failover_instance_rest_required_fields( - request_type=service.FailoverInstanceRequest, -): +def test_inject_fault_rest_required_fields(request_type=service.InjectFaultRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} @@ -14610,7 +15455,7 @@ def test_failover_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).failover_instance._get_unset_required_fields(jsonified_request) + ).inject_fault._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -14619,7 +15464,7 @@ def test_failover_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).failover_instance._get_unset_required_fields(jsonified_request) + ).inject_fault._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -14658,24 +15503,32 @@ def test_failover_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.failover_instance(request) + response = client.inject_fault(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_failover_instance_rest_unset_required_fields(): +def test_inject_fault_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.failover_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.inject_fault._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "faultType", + "name", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_failover_instance_rest_interceptors(null_interceptor): +def test_inject_fault_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14690,15 +15543,13 @@ def test_failover_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_failover_instance" + transports.AlloyDBAdminRestInterceptor, "post_inject_fault" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_failover_instance" + transports.AlloyDBAdminRestInterceptor, "pre_inject_fault" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.FailoverInstanceRequest.pb( - service.FailoverInstanceRequest() - ) + pb_message = service.InjectFaultRequest.pb(service.InjectFaultRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14713,7 +15564,7 @@ def test_failover_instance_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.FailoverInstanceRequest() + request = service.InjectFaultRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -14721,7 +15572,7 @@ def test_failover_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.failover_instance( + client.inject_fault( request, metadata=[ ("key", "val"), @@ -14733,8 +15584,8 @@ def test_failover_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_failover_instance_rest_bad_request( - transport: str = "rest", request_type=service.FailoverInstanceRequest +def test_inject_fault_rest_bad_request( + transport: str = "rest", request_type=service.InjectFaultRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14756,10 +15607,10 @@ def test_failover_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.failover_instance(request) + client.inject_fault(request) -def test_failover_instance_rest_flattened(): +def test_inject_fault_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14777,6 +15628,7 @@ def test_failover_instance_rest_flattened(): # get truthy value for each flattened field mock_args = dict( + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, name="name_value", ) mock_args.update(sample_request) @@ -14788,20 +15640,20 @@ def test_failover_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.failover_instance(**mock_args) + client.inject_fault(**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/*/clusters/*/instances/*}:failover" + "%s/v1beta/{name=projects/*/locations/*/clusters/*/instances/*}:injectFault" % client.transport._host, args[1], ) -def test_failover_instance_rest_flattened_error(transport: str = "rest"): +def test_inject_fault_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14810,13 +15662,14 @@ def test_failover_instance_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.failover_instance( - service.FailoverInstanceRequest(), + client.inject_fault( + service.InjectFaultRequest(), + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, name="name_value", ) -def test_failover_instance_rest_error(): +def test_inject_fault_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -14825,11 +15678,11 @@ def test_failover_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.InjectFaultRequest, + service.RestartInstanceRequest, dict, ], ) -def test_inject_fault_rest(request_type): +def test_restart_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14853,13 +15706,15 @@ def test_inject_fault_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.inject_fault(request) + response = client.restart_instance(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_inject_fault_rest_required_fields(request_type=service.InjectFaultRequest): +def test_restart_instance_rest_required_fields( + request_type=service.RestartInstanceRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} @@ -14874,7 +15729,7 @@ def test_inject_fault_rest_required_fields(request_type=service.InjectFaultReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).inject_fault._get_unset_required_fields(jsonified_request) + ).restart_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -14883,7 +15738,7 @@ def test_inject_fault_rest_required_fields(request_type=service.InjectFaultReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).inject_fault._get_unset_required_fields(jsonified_request) + ).restart_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -14922,32 +15777,24 @@ def test_inject_fault_rest_required_fields(request_type=service.InjectFaultReque response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.inject_fault(request) + response = client.restart_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_inject_fault_rest_unset_required_fields(): +def test_restart_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.inject_fault._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "faultType", - "name", - ) - ) - ) + unset_fields = transport.restart_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_inject_fault_rest_interceptors(null_interceptor): +def test_restart_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14962,13 +15809,13 @@ def test_inject_fault_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_inject_fault" + transports.AlloyDBAdminRestInterceptor, "post_restart_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_inject_fault" + transports.AlloyDBAdminRestInterceptor, "pre_restart_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.InjectFaultRequest.pb(service.InjectFaultRequest()) + pb_message = service.RestartInstanceRequest.pb(service.RestartInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14983,7 +15830,7 @@ def test_inject_fault_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.InjectFaultRequest() + request = service.RestartInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -14991,7 +15838,7 @@ def test_inject_fault_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.inject_fault( + client.restart_instance( request, metadata=[ ("key", "val"), @@ -15003,8 +15850,8 @@ def test_inject_fault_rest_interceptors(null_interceptor): post.assert_called_once() -def test_inject_fault_rest_bad_request( - transport: str = "rest", request_type=service.InjectFaultRequest +def test_restart_instance_rest_bad_request( + transport: str = "rest", request_type=service.RestartInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15026,10 +15873,10 @@ def test_inject_fault_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.inject_fault(request) + client.restart_instance(request) -def test_inject_fault_rest_flattened(): +def test_restart_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15047,7 +15894,6 @@ def test_inject_fault_rest_flattened(): # get truthy value for each flattened field mock_args = dict( - fault_type=service.InjectFaultRequest.FaultType.STOP_VM, name="name_value", ) mock_args.update(sample_request) @@ -15059,20 +15905,20 @@ def test_inject_fault_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.inject_fault(**mock_args) + client.restart_instance(**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/*/clusters/*/instances/*}:injectFault" + "%s/v1beta/{name=projects/*/locations/*/clusters/*/instances/*}:restart" % client.transport._host, args[1], ) -def test_inject_fault_rest_flattened_error(transport: str = "rest"): +def test_restart_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15081,14 +15927,13 @@ def test_inject_fault_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.inject_fault( - service.InjectFaultRequest(), - fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + client.restart_instance( + service.RestartInstanceRequest(), name="name_value", ) -def test_inject_fault_rest_error(): +def test_restart_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -15097,47 +15942,50 @@ def test_inject_fault_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.RestartInstanceRequest, + service.ListBackupsRequest, dict, ], ) -def test_restart_instance_rest(request_type): +def test_list_backups_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + 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 = operations_pb2.Operation(name="operations/spam") + return_value = service.ListBackupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = service.ListBackupsResponse.pb(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.restart_instance(request) + response = client.list_backups(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, pagers.ListBackupsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_restart_instance_rest_required_fields( - request_type=service.RestartInstanceRequest, -): +def test_list_backups_rest_required_fields(request_type=service.ListBackupsRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15148,21 +15996,30 @@ def test_restart_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).restart_instance._get_unset_required_fields(jsonified_request) + ).list_backups._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() - ).restart_instance._get_unset_required_fields(jsonified_request) + ).list_backups._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 "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15171,7 +16028,7 @@ def test_restart_instance_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 = service.ListBackupsResponse() # 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 @@ -15183,37 +16040,49 @@ def test_restart_instance_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 = service.ListBackupsResponse.pb(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.restart_instance(request) + response = client.list_backups(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_restart_instance_rest_unset_required_fields(): +def test_list_backups_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.restart_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_backups._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_restart_instance_rest_interceptors(null_interceptor): +def test_list_backups_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15226,15 +16095,13 @@ def test_restart_instance_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_restart_instance" + transports.AlloyDBAdminRestInterceptor, "post_list_backups" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_restart_instance" + transports.AlloyDBAdminRestInterceptor, "pre_list_backups" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.RestartInstanceRequest.pb(service.RestartInstanceRequest()) + pb_message = service.ListBackupsRequest.pb(service.ListBackupsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15245,19 +16112,19 @@ def test_restart_instance_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = service.ListBackupsResponse.to_json( + service.ListBackupsResponse() ) - request = service.RestartInstanceRequest() + request = service.ListBackupsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = service.ListBackupsResponse() - client.restart_instance( + client.list_backups( request, metadata=[ ("key", "val"), @@ -15269,8 +16136,8 @@ def test_restart_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_restart_instance_rest_bad_request( - transport: str = "rest", request_type=service.RestartInstanceRequest +def test_list_backups_rest_bad_request( + transport: str = "rest", request_type=service.ListBackupsRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15278,9 +16145,7 @@ def test_restart_instance_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + 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. @@ -15292,10 +16157,10 @@ def test_restart_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.restart_instance(request) + client.list_backups(request) -def test_restart_instance_rest_flattened(): +def test_list_backups_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15304,40 +16169,40 @@ def test_restart_instance_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 = service.ListBackupsResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + 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 = service.ListBackupsResponse.pb(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.restart_instance(**mock_args) + client.list_backups(**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/*/clusters/*/instances/*}:restart" + "%s/v1beta/{parent=projects/*/locations/*}/backups" % client.transport._host, args[1], ) -def test_restart_instance_rest_flattened_error(transport: str = "rest"): +def test_list_backups_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15346,65 +16211,142 @@ def test_restart_instance_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.restart_instance( - service.RestartInstanceRequest(), - name="name_value", + client.list_backups( + service.ListBackupsRequest(), + parent="parent_value", ) -def test_restart_instance_rest_error(): +def test_list_backups_rest_pager(transport: str = "rest"): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token="abc", + ), + service.ListBackupsResponse( + backups=[], + next_page_token="def", + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token="ghi", + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListBackupsResponse.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_backups(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Backup) for i in results) + + pages = list(client.list_backups(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - service.ListBackupsRequest, + service.GetBackupRequest, dict, ], ) -def test_list_backups_rest(request_type): +def test_get_backup_rest(request_type): client = AlloyDBAdminClient( 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/backups/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 = service.ListBackupsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + return_value = resources.Backup( + name="name_value", + display_name="display_name_value", + uid="uid_value", + state=resources.Backup.State.READY, + type_=resources.Backup.Type.ON_DEMAND, + description="description_value", + cluster_uid="cluster_uid_value", + cluster_name="cluster_name_value", + reconciling=True, + etag="etag_value", + size_bytes=1089, + satisfies_pzs=True, + database_version=resources.DatabaseVersion.POSTGRES_13, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListBackupsResponse.pb(return_value) + return_value = resources.Backup.pb(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_backups(request) + response = client.get_backup(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, resources.Backup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.uid == "uid_value" + assert response.state == resources.Backup.State.READY + assert response.type_ == resources.Backup.Type.ON_DEMAND + assert response.description == "description_value" + assert response.cluster_uid == "cluster_uid_value" + assert response.cluster_name == "cluster_name_value" + assert response.reconciling is True + assert response.etag == "etag_value" + assert response.size_bytes == 1089 + assert response.satisfies_pzs is True + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 -def test_list_backups_rest_required_fields(request_type=service.ListBackupsRequest): +def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15415,30 +16357,21 @@ def test_list_backups_rest_required_fields(request_type=service.ListBackupsReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_backups._get_unset_required_fields(jsonified_request) + ).get_backup._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" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_backups._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", - ) - ) + ).get_backup._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" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15447,7 +16380,7 @@ def test_list_backups_rest_required_fields(request_type=service.ListBackupsReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListBackupsResponse() + return_value = resources.Backup() # 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 @@ -15468,40 +16401,30 @@ def test_list_backups_rest_required_fields(request_type=service.ListBackupsReque response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListBackupsResponse.pb(return_value) + return_value = resources.Backup.pb(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_backups(request) + response = client.get_backup(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_backups_rest_unset_required_fields(): +def test_get_backup_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_backups._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.get_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_backups_rest_interceptors(null_interceptor): +def test_get_backup_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15514,13 +16437,13 @@ def test_list_backups_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_list_backups" + transports.AlloyDBAdminRestInterceptor, "post_get_backup" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_list_backups" + transports.AlloyDBAdminRestInterceptor, "pre_get_backup" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListBackupsRequest.pb(service.ListBackupsRequest()) + pb_message = service.GetBackupRequest.pb(service.GetBackupRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15531,19 +16454,17 @@ def test_list_backups_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = service.ListBackupsResponse.to_json( - service.ListBackupsResponse() - ) + req.return_value._content = resources.Backup.to_json(resources.Backup()) - request = service.ListBackupsRequest() + request = service.GetBackupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListBackupsResponse() + post.return_value = resources.Backup() - client.list_backups( + client.get_backup( request, metadata=[ ("key", "val"), @@ -15555,8 +16476,8 @@ def test_list_backups_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_backups_rest_bad_request( - transport: str = "rest", request_type=service.ListBackupsRequest +def test_get_backup_rest_bad_request( + transport: str = "rest", request_type=service.GetBackupRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15564,7 +16485,7 @@ def test_list_backups_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -15576,10 +16497,10 @@ def test_list_backups_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_backups(request) + client.get_backup(request) -def test_list_backups_rest_flattened(): +def test_get_backup_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15588,14 +16509,14 @@ def test_list_backups_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 = service.ListBackupsResponse() + return_value = resources.Backup() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {"name": "projects/sample1/locations/sample2/backups/sample3"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) @@ -15603,167 +16524,180 @@ def test_list_backups_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListBackupsResponse.pb(return_value) + return_value = resources.Backup.pb(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_backups(**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/*}/backups" - % client.transport._host, - args[1], - ) - - -def test_list_backups_rest_flattened_error(transport: str = "rest"): - client = AlloyDBAdminClient( - 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_backups( - service.ListBackupsRequest(), - parent="parent_value", - ) - - -def test_list_backups_rest_pager(transport: str = "rest"): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListBackupsResponse( - backups=[ - resources.Backup(), - resources.Backup(), - resources.Backup(), - ], - next_page_token="abc", - ), - service.ListBackupsResponse( - backups=[], - next_page_token="def", - ), - service.ListBackupsResponse( - backups=[ - resources.Backup(), - ], - next_page_token="ghi", - ), - service.ListBackupsResponse( - backups=[ - resources.Backup(), - resources.Backup(), - ], - ), + client.get_backup(**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/*/backups/*}" + % client.transport._host, + args[1], ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple(service.ListBackupsResponse.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"} +def test_get_backup_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - pager = client.list_backups(request=sample_request) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_backup( + service.GetBackupRequest(), + name="name_value", + ) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Backup) for i in results) - pages = list(client.list_backups(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token +def test_get_backup_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( "request_type", [ - service.GetBackupRequest, + service.CreateBackupRequest, dict, ], ) -def test_get_backup_rest(request_type): +def test_create_backup_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["backup"] = { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "type_": 1, + "description": "description_value", + "cluster_uid": "cluster_uid_value", + "cluster_name": "cluster_name_value", + "reconciling": True, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "etag": "etag_value", + "annotations": {}, + "size_bytes": 1089, + "expiry_time": {}, + "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, + "satisfies_pzs": True, + "database_version": 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 = service.CreateBackupRequest.meta.fields["backup"] + + 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["backup"].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["backup"][field])): + del request_init["backup"][field][i][subfield] + else: + del request_init["backup"][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 = resources.Backup( - name="name_value", - display_name="display_name_value", - uid="uid_value", - state=resources.Backup.State.READY, - type_=resources.Backup.Type.ON_DEMAND, - description="description_value", - cluster_uid="cluster_uid_value", - cluster_name="cluster_name_value", - reconciling=True, - etag="etag_value", - size_bytes=1089, - database_version=resources.DatabaseVersion.POSTGRES_13, - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Backup.pb(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_backup(request) + response = client.create_backup(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Backup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.uid == "uid_value" - assert response.state == resources.Backup.State.READY - assert response.type_ == resources.Backup.Type.ON_DEMAND - assert response.description == "description_value" - assert response.cluster_uid == "cluster_uid_value" - assert response.cluster_name == "cluster_name_value" - assert response.reconciling is True - assert response.etag == "etag_value" - assert response.size_bytes == 1089 - assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + assert response.operation.name == "operations/spam" -def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): +def test_create_backup_rest_required_fields(request_type=service.CreateBackupRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["backup_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15771,24 +16705,38 @@ def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): ) # verify fields with default values are dropped + assert "backupId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_backup._get_unset_required_fields(jsonified_request) + ).create_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "backupId" in jsonified_request + assert jsonified_request["backupId"] == request_init["backup_id"] - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["backupId"] = "backup_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_backup._get_unset_required_fields(jsonified_request) + ).create_backup._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "backup_id", + "request_id", + "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 "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "backupId" in jsonified_request + assert jsonified_request["backupId"] == "backup_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15797,7 +16745,7 @@ def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Backup() + 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 @@ -15809,39 +16757,58 @@ def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): 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 = resources.Backup.pb(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_backup(request) + response = client.create_backup(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "backupId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_backup_rest_unset_required_fields(): +def test_create_backup_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_backup._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_backup._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "backupId", + "requestId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "backupId", + "backup", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_backup_rest_interceptors(null_interceptor): +def test_create_backup_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15854,13 +16821,15 @@ def test_get_backup_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_get_backup" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_create_backup" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_get_backup" + transports.AlloyDBAdminRestInterceptor, "pre_create_backup" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.GetBackupRequest.pb(service.GetBackupRequest()) + pb_message = service.CreateBackupRequest.pb(service.CreateBackupRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15871,17 +16840,19 @@ def test_get_backup_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.Backup.to_json(resources.Backup()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) - request = service.GetBackupRequest() + request = service.CreateBackupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Backup() + post.return_value = operations_pb2.Operation() - client.get_backup( + client.create_backup( request, metadata=[ ("key", "val"), @@ -15893,8 +16864,8 @@ def test_get_backup_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_backup_rest_bad_request( - transport: str = "rest", request_type=service.GetBackupRequest +def test_create_backup_rest_bad_request( + transport: str = "rest", request_type=service.CreateBackupRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15902,7 +16873,7 @@ def test_get_backup_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backups/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. @@ -15914,10 +16885,10 @@ def test_get_backup_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_backup(request) + client.create_backup(request) -def test_get_backup_rest_flattened(): +def test_create_backup_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15926,40 +16897,40 @@ def test_get_backup_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 = resources.Backup() + 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/backups/sample3"} + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + backup=resources.Backup(name="name_value"), + backup_id="backup_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 = resources.Backup.pb(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_backup(**mock_args) + client.create_backup(**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/*/backups/*}" + "%s/v1beta/{parent=projects/*/locations/*}/backups" % client.transport._host, args[1], ) -def test_get_backup_rest_flattened_error(transport: str = "rest"): +def test_create_backup_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15968,13 +16939,15 @@ def test_get_backup_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.get_backup( - service.GetBackupRequest(), - name="name_value", + client.create_backup( + service.CreateBackupRequest(), + parent="parent_value", + backup=resources.Backup(name="name_value"), + backup_id="backup_id_value", ) -def test_get_backup_rest_error(): +def test_create_backup_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -15983,20 +16956,22 @@ def test_get_backup_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.CreateBackupRequest, + service.UpdateBackupRequest, dict, ], ) -def test_create_backup_rest(request_type): +def test_update_backup_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} + } request_init["backup"] = { - "name": "name_value", + "name": "projects/sample1/locations/sample2/backups/sample3", "display_name": "display_name_value", "uid": "uid_value", "create_time": {"seconds": 751, "nanos": 543}, @@ -16019,6 +16994,7 @@ def test_create_backup_rest(request_type): "size_bytes": 1089, "expiry_time": {}, "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, + "satisfies_pzs": True, "database_version": 1, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -16026,7 +17002,7 @@ def test_create_backup_rest(request_type): # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = service.CreateBackupRequest.meta.fields["backup"] + test_field = service.UpdateBackupRequest.meta.fields["backup"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -16102,18 +17078,16 @@ def get_message_fields(field): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_backup(request) + response = client.update_backup(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_create_backup_rest_required_fields(request_type=service.CreateBackupRequest): +def test_update_backup_rest_required_fields(request_type=service.UpdateBackupRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" - request_init["backup_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16121,38 +17095,29 @@ def test_create_backup_rest_required_fields(request_type=service.CreateBackupReq ) # verify fields with default values are dropped - assert "backupId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_backup._get_unset_required_fields(jsonified_request) + ).update_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "backupId" in jsonified_request - assert jsonified_request["backupId"] == request_init["backup_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["backupId"] = "backup_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_backup._get_unset_required_fields(jsonified_request) + ).update_backup._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "backup_id", + "allow_missing", "request_id", + "update_mask", "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 "backupId" in jsonified_request - assert jsonified_request["backupId"] == "backup_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16173,7 +17138,7 @@ def test_create_backup_rest_required_fields(request_type=service.CreateBackupReq 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 @@ -16186,45 +17151,34 @@ def test_create_backup_rest_required_fields(request_type=service.CreateBackupReq response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_backup(request) + response = client.update_backup(request) - expected_params = [ - ( - "backupId", - "", - ), - ("$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_create_backup_rest_unset_required_fields(): +def test_update_backup_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_backup._get_unset_required_fields({}) + unset_fields = transport.update_backup._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "backupId", + "allowMissing", "requestId", + "updateMask", "validateOnly", ) ) - & set( - ( - "parent", - "backupId", - "backup", - ) - ) + & set(("backup",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_backup_rest_interceptors(null_interceptor): +def test_update_backup_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -16239,13 +17193,13 @@ def test_create_backup_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_create_backup" + transports.AlloyDBAdminRestInterceptor, "post_update_backup" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_create_backup" + transports.AlloyDBAdminRestInterceptor, "pre_update_backup" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.CreateBackupRequest.pb(service.CreateBackupRequest()) + pb_message = service.UpdateBackupRequest.pb(service.UpdateBackupRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -16260,7 +17214,7 @@ def test_create_backup_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.CreateBackupRequest() + request = service.UpdateBackupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -16268,7 +17222,7 @@ def test_create_backup_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_backup( + client.update_backup( request, metadata=[ ("key", "val"), @@ -16280,8 +17234,8 @@ def test_create_backup_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_backup_rest_bad_request( - transport: str = "rest", request_type=service.CreateBackupRequest +def test_update_backup_rest_bad_request( + transport: str = "rest", request_type=service.UpdateBackupRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16289,7 +17243,9 @@ def test_create_backup_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -16301,10 +17257,10 @@ def test_create_backup_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_backup(request) + client.update_backup(request) -def test_create_backup_rest_flattened(): +def test_update_backup_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16316,13 +17272,14 @@ def test_create_backup_rest_flattened(): 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"} + sample_request = { + "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", backup=resources.Backup(name="name_value"), - backup_id="backup_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -16333,20 +17290,20 @@ def test_create_backup_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_backup(**mock_args) + client.update_backup(**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/*}/backups" + "%s/v1beta/{backup.name=projects/*/locations/*/backups/*}" % client.transport._host, args[1], ) -def test_create_backup_rest_flattened_error(transport: str = "rest"): +def test_update_backup_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16355,15 +17312,14 @@ def test_create_backup_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.create_backup( - service.CreateBackupRequest(), - parent="parent_value", + client.update_backup( + service.UpdateBackupRequest(), backup=resources.Backup(name="name_value"), - backup_id="backup_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_create_backup_rest_error(): +def test_update_backup_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -16372,113 +17328,18 @@ def test_create_backup_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.UpdateBackupRequest, + service.DeleteBackupRequest, dict, ], ) -def test_update_backup_rest(request_type): +def test_delete_backup_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} - } - request_init["backup"] = { - "name": "projects/sample1/locations/sample2/backups/sample3", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "type_": 1, - "description": "description_value", - "cluster_uid": "cluster_uid_value", - "cluster_name": "cluster_name_value", - "reconciling": True, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "etag": "etag_value", - "annotations": {}, - "size_bytes": 1089, - "expiry_time": {}, - "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, - "database_version": 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 = service.UpdateBackupRequest.meta.fields["backup"] - - 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["backup"].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["backup"][field])): - del request_init["backup"][field][i][subfield] - else: - del request_init["backup"][field][subfield] + request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -16493,16 +17354,17 @@ def get_message_fields(field): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_backup(request) + response = client.delete_backup(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_update_backup_rest_required_fields(request_type=service.UpdateBackupRequest): +def test_delete_backup_rest_required_fields(request_type=service.DeleteBackupRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16513,26 +17375,29 @@ def test_update_backup_rest_required_fields(request_type=service.UpdateBackupReq unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_backup._get_unset_required_fields(jsonified_request) + ).delete_backup._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_backup._get_unset_required_fields(jsonified_request) + ).delete_backup._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", "request_id", - "update_mask", "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 = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16553,10 +17418,9 @@ def test_update_backup_rest_required_fields(request_type=service.UpdateBackupReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -16566,34 +17430,33 @@ def test_update_backup_rest_required_fields(request_type=service.UpdateBackupReq response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_backup(request) + response = client.delete_backup(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_backup_rest_unset_required_fields(): +def test_delete_backup_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_backup._get_unset_required_fields({}) + unset_fields = transport.delete_backup._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "allowMissing", + "etag", "requestId", - "updateMask", "validateOnly", ) ) - & set(("backup",)) + & set(("name",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_backup_rest_interceptors(null_interceptor): +def test_delete_backup_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -16608,13 +17471,13 @@ def test_update_backup_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_update_backup" + transports.AlloyDBAdminRestInterceptor, "post_delete_backup" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_update_backup" + transports.AlloyDBAdminRestInterceptor, "pre_delete_backup" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.UpdateBackupRequest.pb(service.UpdateBackupRequest()) + pb_message = service.DeleteBackupRequest.pb(service.DeleteBackupRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -16629,7 +17492,7 @@ def test_update_backup_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.UpdateBackupRequest() + request = service.DeleteBackupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -16637,7 +17500,7 @@ def test_update_backup_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.update_backup( + client.delete_backup( request, metadata=[ ("key", "val"), @@ -16649,8 +17512,8 @@ def test_update_backup_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_backup_rest_bad_request( - transport: str = "rest", request_type=service.UpdateBackupRequest +def test_delete_backup_rest_bad_request( + transport: str = "rest", request_type=service.DeleteBackupRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16658,9 +17521,7 @@ def test_update_backup_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} - } + request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -16672,10 +17533,10 @@ def test_update_backup_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_backup(request) + client.delete_backup(request) -def test_update_backup_rest_flattened(): +def test_delete_backup_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16687,14 +17548,11 @@ def test_update_backup_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = { - "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} - } + sample_request = {"name": "projects/sample1/locations/sample2/backups/sample3"} # get truthy value for each flattened field mock_args = dict( - backup=resources.Backup(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -16705,20 +17563,20 @@ def test_update_backup_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_backup(**mock_args) + client.delete_backup(**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/{backup.name=projects/*/locations/*/backups/*}" + "%s/v1beta/{name=projects/*/locations/*/backups/*}" % client.transport._host, args[1], ) -def test_update_backup_rest_flattened_error(transport: str = "rest"): +def test_delete_backup_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16727,14 +17585,13 @@ def test_update_backup_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_backup( - service.UpdateBackupRequest(), - backup=resources.Backup(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_backup( + service.DeleteBackupRequest(), + name="name_value", ) -def test_update_backup_rest_error(): +def test_delete_backup_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -16743,43 +17600,50 @@ def test_update_backup_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.DeleteBackupRequest, + service.ListSupportedDatabaseFlagsRequest, dict, ], ) -def test_delete_backup_rest(request_type): +def test_list_supported_database_flags_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backups/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 = operations_pb2.Operation(name="operations/spam") + return_value = service.ListSupportedDatabaseFlagsResponse( + next_page_token="next_page_token_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 = service.ListSupportedDatabaseFlagsResponse.pb(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.delete_backup(request) + response = client.list_supported_database_flags(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, pagers.ListSupportedDatabaseFlagsPager) + assert response.next_page_token == "next_page_token_value" -def test_delete_backup_rest_required_fields(request_type=service.DeleteBackupRequest): +def test_list_supported_database_flags_rest_required_fields( + request_type=service.ListSupportedDatabaseFlagsRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16790,29 +17654,28 @@ def test_delete_backup_rest_required_fields(request_type=service.DeleteBackupReq unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_backup._get_unset_required_fields(jsonified_request) + ).list_supported_database_flags._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_backup._get_unset_required_fields(jsonified_request) + ).list_supported_database_flags._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "etag", - "request_id", - "validate_only", + "page_size", + "page_token", ) ) 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 = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16821,7 +17684,7 @@ def test_delete_backup_rest_required_fields(request_type=service.DeleteBackupReq request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListSupportedDatabaseFlagsResponse() # 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 @@ -16833,45 +17696,49 @@ def test_delete_backup_rest_required_fields(request_type=service.DeleteBackupReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "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 = service.ListSupportedDatabaseFlagsResponse.pb(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.delete_backup(request) + response = client.list_supported_database_flags(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_backup_rest_unset_required_fields(): +def test_list_supported_database_flags_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_backup._get_unset_required_fields({}) + unset_fields = transport.list_supported_database_flags._get_unset_required_fields( + {} + ) assert set(unset_fields) == ( set( ( - "etag", - "requestId", - "validateOnly", + "pageSize", + "pageToken", ) ) - & set(("name",)) + & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_backup_rest_interceptors(null_interceptor): +def test_list_supported_database_flags_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -16884,15 +17751,15 @@ def test_delete_backup_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_delete_backup" + transports.AlloyDBAdminRestInterceptor, "post_list_supported_database_flags" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_delete_backup" + transports.AlloyDBAdminRestInterceptor, "pre_list_supported_database_flags" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.DeleteBackupRequest.pb(service.DeleteBackupRequest()) + pb_message = service.ListSupportedDatabaseFlagsRequest.pb( + service.ListSupportedDatabaseFlagsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -16903,19 +17770,19 @@ def test_delete_backup_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = service.ListSupportedDatabaseFlagsResponse.to_json( + service.ListSupportedDatabaseFlagsResponse() ) - request = service.DeleteBackupRequest() + request = service.ListSupportedDatabaseFlagsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = service.ListSupportedDatabaseFlagsResponse() - client.delete_backup( + client.list_supported_database_flags( request, metadata=[ ("key", "val"), @@ -16927,8 +17794,8 @@ def test_delete_backup_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_backup_rest_bad_request( - transport: str = "rest", request_type=service.DeleteBackupRequest +def test_list_supported_database_flags_rest_bad_request( + transport: str = "rest", request_type=service.ListSupportedDatabaseFlagsRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16936,7 +17803,7 @@ def test_delete_backup_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backups/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. @@ -16948,10 +17815,10 @@ def test_delete_backup_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_backup(request) + client.list_supported_database_flags(request) -def test_delete_backup_rest_flattened(): +def test_list_supported_database_flags_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16960,38 +17827,40 @@ def test_delete_backup_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 = service.ListSupportedDatabaseFlagsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/backups/sample3"} + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + 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 = service.ListSupportedDatabaseFlagsResponse.pb(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.delete_backup(**mock_args) + client.list_supported_database_flags(**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/*/backups/*}" + "%s/v1beta/{parent=projects/*/locations/*}/supportedDatabaseFlags" % client.transport._host, args[1], ) -def test_delete_backup_rest_flattened_error(transport: str = "rest"): +def test_list_supported_database_flags_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17000,60 +17869,121 @@ def test_delete_backup_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_backup( - service.DeleteBackupRequest(), - name="name_value", + client.list_supported_database_flags( + service.ListSupportedDatabaseFlagsRequest(), + parent="parent_value", ) -def test_delete_backup_rest_error(): +def test_list_supported_database_flags_rest_pager(transport: str = "rest"): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token="abc", + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token="def", + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token="ghi", + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListSupportedDatabaseFlagsResponse.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_supported_database_flags(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.SupportedDatabaseFlag) for i in results) + + pages = list(client.list_supported_database_flags(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - service.ListSupportedDatabaseFlagsRequest, + service.GenerateClientCertificateRequest, dict, ], ) -def test_list_supported_database_flags_rest(request_type): +def test_generate_client_certificate_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"parent": "projects/sample1/locations/sample2/clusters/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 = service.ListSupportedDatabaseFlagsResponse( - next_page_token="next_page_token_value", + return_value = service.GenerateClientCertificateResponse( + pem_certificate="pem_certificate_value", + pem_certificate_chain=["pem_certificate_chain_value"], + ca_cert="ca_cert_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 = service.ListSupportedDatabaseFlagsResponse.pb(return_value) + return_value = service.GenerateClientCertificateResponse.pb(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_supported_database_flags(request) + response = client.generate_client_certificate(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSupportedDatabaseFlagsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, service.GenerateClientCertificateResponse) + assert response.pem_certificate == "pem_certificate_value" + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + assert response.ca_cert == "ca_cert_value" -def test_list_supported_database_flags_rest_required_fields( - request_type=service.ListSupportedDatabaseFlagsRequest, +def test_generate_client_certificate_rest_required_fields( + request_type=service.GenerateClientCertificateRequest, ): transport_class = transports.AlloyDBAdminRestTransport @@ -17069,7 +17999,7 @@ def test_list_supported_database_flags_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_supported_database_flags._get_unset_required_fields(jsonified_request) + ).generate_client_certificate._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -17078,14 +18008,7 @@ def test_list_supported_database_flags_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_supported_database_flags._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", - ) - ) + ).generate_client_certificate._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -17099,7 +18022,7 @@ def test_list_supported_database_flags_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListSupportedDatabaseFlagsResponse() + return_value = service.GenerateClientCertificateResponse() # 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 @@ -17111,49 +18034,40 @@ def test_list_supported_database_flags_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 = service.ListSupportedDatabaseFlagsResponse.pb(return_value) + return_value = service.GenerateClientCertificateResponse.pb(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_supported_database_flags(request) + response = client.generate_client_certificate(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_supported_database_flags_rest_unset_required_fields(): +def test_generate_client_certificate_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_supported_database_flags._get_unset_required_fields( - {} - ) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.generate_client_certificate._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_supported_database_flags_rest_interceptors(null_interceptor): +def test_generate_client_certificate_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -17166,14 +18080,14 @@ def test_list_supported_database_flags_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_list_supported_database_flags" + transports.AlloyDBAdminRestInterceptor, "post_generate_client_certificate" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_list_supported_database_flags" + transports.AlloyDBAdminRestInterceptor, "pre_generate_client_certificate" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListSupportedDatabaseFlagsRequest.pb( - service.ListSupportedDatabaseFlagsRequest() + pb_message = service.GenerateClientCertificateRequest.pb( + service.GenerateClientCertificateRequest() ) transcode.return_value = { "method": "post", @@ -17185,19 +18099,19 @@ def test_list_supported_database_flags_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = service.ListSupportedDatabaseFlagsResponse.to_json( - service.ListSupportedDatabaseFlagsResponse() + req.return_value._content = service.GenerateClientCertificateResponse.to_json( + service.GenerateClientCertificateResponse() ) - request = service.ListSupportedDatabaseFlagsRequest() + request = service.GenerateClientCertificateRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListSupportedDatabaseFlagsResponse() + post.return_value = service.GenerateClientCertificateResponse() - client.list_supported_database_flags( + client.generate_client_certificate( request, metadata=[ ("key", "val"), @@ -17209,8 +18123,8 @@ def test_list_supported_database_flags_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_supported_database_flags_rest_bad_request( - transport: str = "rest", request_type=service.ListSupportedDatabaseFlagsRequest +def test_generate_client_certificate_rest_bad_request( + transport: str = "rest", request_type=service.GenerateClientCertificateRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -17218,7 +18132,7 @@ def test_list_supported_database_flags_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -17230,10 +18144,10 @@ def test_list_supported_database_flags_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_supported_database_flags(request) + client.generate_client_certificate(request) -def test_list_supported_database_flags_rest_flattened(): +def test_generate_client_certificate_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -17242,10 +18156,12 @@ def test_list_supported_database_flags_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 = service.ListSupportedDatabaseFlagsResponse() + return_value = service.GenerateClientCertificateResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "parent": "projects/sample1/locations/sample2/clusters/sample3" + } # get truthy value for each flattened field mock_args = dict( @@ -17257,25 +18173,25 @@ def test_list_supported_database_flags_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListSupportedDatabaseFlagsResponse.pb(return_value) + return_value = service.GenerateClientCertificateResponse.pb(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_supported_database_flags(**mock_args) + client.generate_client_certificate(**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/*}/supportedDatabaseFlags" + "%s/v1beta/{parent=projects/*/locations/*/clusters/*}:generateClientCertificate" % client.transport._host, args[1], ) -def test_list_supported_database_flags_rest_flattened_error(transport: str = "rest"): +def test_generate_client_certificate_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17284,121 +18200,72 @@ def test_list_supported_database_flags_rest_flattened_error(transport: str = "re # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_supported_database_flags( - service.ListSupportedDatabaseFlagsRequest(), + client.generate_client_certificate( + service.GenerateClientCertificateRequest(), parent="parent_value", ) -def test_list_supported_database_flags_rest_pager(transport: str = "rest"): +def test_generate_client_certificate_rest_error(): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), 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 = ( - service.ListSupportedDatabaseFlagsResponse( - supported_database_flags=[ - resources.SupportedDatabaseFlag(), - resources.SupportedDatabaseFlag(), - resources.SupportedDatabaseFlag(), - ], - next_page_token="abc", - ), - service.ListSupportedDatabaseFlagsResponse( - supported_database_flags=[], - next_page_token="def", - ), - service.ListSupportedDatabaseFlagsResponse( - supported_database_flags=[ - resources.SupportedDatabaseFlag(), - ], - next_page_token="ghi", - ), - service.ListSupportedDatabaseFlagsResponse( - supported_database_flags=[ - resources.SupportedDatabaseFlag(), - resources.SupportedDatabaseFlag(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - service.ListSupportedDatabaseFlagsResponse.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_supported_database_flags(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.SupportedDatabaseFlag) for i in results) - - pages = list(client.list_supported_database_flags(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - service.GenerateClientCertificateRequest, + service.GetConnectionInfoRequest, dict, ], ) -def test_generate_client_certificate_rest(request_type): +def test_get_connection_info_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = { + "parent": "projects/sample1/locations/sample2/clusters/sample3/instances/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 = service.GenerateClientCertificateResponse( - pem_certificate="pem_certificate_value", + return_value = resources.ConnectionInfo( + name="name_value", + ip_address="ip_address_value", + public_ip_address="public_ip_address_value", pem_certificate_chain=["pem_certificate_chain_value"], - ca_cert="ca_cert_value", + instance_uid="instance_uid_value", + psc_dns_name="psc_dns_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 = service.GenerateClientCertificateResponse.pb(return_value) + return_value = resources.ConnectionInfo.pb(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_client_certificate(request) + response = client.get_connection_info(request) # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateClientCertificateResponse) - assert response.pem_certificate == "pem_certificate_value" + assert isinstance(response, resources.ConnectionInfo) + assert response.name == "name_value" + assert response.ip_address == "ip_address_value" + assert response.public_ip_address == "public_ip_address_value" assert response.pem_certificate_chain == ["pem_certificate_chain_value"] - assert response.ca_cert == "ca_cert_value" + assert response.instance_uid == "instance_uid_value" + assert response.psc_dns_name == "psc_dns_name_value" -def test_generate_client_certificate_rest_required_fields( - request_type=service.GenerateClientCertificateRequest, +def test_get_connection_info_rest_required_fields( + request_type=service.GetConnectionInfoRequest, ): transport_class = transports.AlloyDBAdminRestTransport @@ -17414,7 +18281,7 @@ def test_generate_client_certificate_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).generate_client_certificate._get_unset_required_fields(jsonified_request) + ).get_connection_info._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -17423,7 +18290,9 @@ def test_generate_client_certificate_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).generate_client_certificate._get_unset_required_fields(jsonified_request) + ).get_connection_info._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -17437,7 +18306,7 @@ def test_generate_client_certificate_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.GenerateClientCertificateResponse() + return_value = resources.ConnectionInfo() # 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 @@ -17449,40 +18318,39 @@ def test_generate_client_certificate_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 = service.GenerateClientCertificateResponse.pb(return_value) + return_value = resources.ConnectionInfo.pb(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_client_certificate(request) + response = client.get_connection_info(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_generate_client_certificate_rest_unset_required_fields(): +def test_get_connection_info_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.generate_client_certificate._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent",))) + unset_fields = transport.get_connection_info._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("parent",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_client_certificate_rest_interceptors(null_interceptor): +def test_get_connection_info_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -17495,14 +18363,14 @@ def test_generate_client_certificate_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_generate_client_certificate" + transports.AlloyDBAdminRestInterceptor, "post_get_connection_info" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_generate_client_certificate" + transports.AlloyDBAdminRestInterceptor, "pre_get_connection_info" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.GenerateClientCertificateRequest.pb( - service.GenerateClientCertificateRequest() + pb_message = service.GetConnectionInfoRequest.pb( + service.GetConnectionInfoRequest() ) transcode.return_value = { "method": "post", @@ -17514,19 +18382,19 @@ def test_generate_client_certificate_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = service.GenerateClientCertificateResponse.to_json( - service.GenerateClientCertificateResponse() + req.return_value._content = resources.ConnectionInfo.to_json( + resources.ConnectionInfo() ) - request = service.GenerateClientCertificateRequest() + request = service.GetConnectionInfoRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.GenerateClientCertificateResponse() + post.return_value = resources.ConnectionInfo() - client.generate_client_certificate( + client.get_connection_info( request, metadata=[ ("key", "val"), @@ -17538,8 +18406,8 @@ def test_generate_client_certificate_rest_interceptors(null_interceptor): post.assert_called_once() -def test_generate_client_certificate_rest_bad_request( - transport: str = "rest", request_type=service.GenerateClientCertificateRequest +def test_get_connection_info_rest_bad_request( + transport: str = "rest", request_type=service.GetConnectionInfoRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -17547,7 +18415,9 @@ def test_generate_client_certificate_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = { + "parent": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -17559,10 +18429,10 @@ def test_generate_client_certificate_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.generate_client_certificate(request) + client.get_connection_info(request) -def test_generate_client_certificate_rest_flattened(): +def test_get_connection_info_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -17571,11 +18441,11 @@ def test_generate_client_certificate_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 = service.GenerateClientCertificateResponse() + return_value = resources.ConnectionInfo() # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/clusters/sample3" + "parent": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } # get truthy value for each flattened field @@ -17588,25 +18458,25 @@ def test_generate_client_certificate_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.GenerateClientCertificateResponse.pb(return_value) + return_value = resources.ConnectionInfo.pb(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.generate_client_certificate(**mock_args) + client.get_connection_info(**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/*/clusters/*}:generateClientCertificate" + "%s/v1beta/{parent=projects/*/locations/*/clusters/*/instances/*}/connectionInfo" % client.transport._host, args[1], ) -def test_generate_client_certificate_rest_flattened_error(transport: str = "rest"): +def test_get_connection_info_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17615,13 +18485,13 @@ def test_generate_client_certificate_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.generate_client_certificate( - service.GenerateClientCertificateRequest(), + client.get_connection_info( + service.GetConnectionInfoRequest(), parent="parent_value", ) -def test_generate_client_certificate_rest_error(): +def test_get_connection_info_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -17630,54 +18500,46 @@ def test_generate_client_certificate_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.GetConnectionInfoRequest, + service.ListUsersRequest, dict, ], ) -def test_get_connection_info_rest(request_type): +def test_list_users_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + request_init = {"parent": "projects/sample1/locations/sample2/clusters/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 = resources.ConnectionInfo( - name="name_value", - ip_address="ip_address_value", - pem_certificate_chain=["pem_certificate_chain_value"], - instance_uid="instance_uid_value", + return_value = service.ListUsersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = resources.ConnectionInfo.pb(return_value) + return_value = service.ListUsersResponse.pb(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_connection_info(request) + response = client.list_users(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.ConnectionInfo) - assert response.name == "name_value" - assert response.ip_address == "ip_address_value" - assert response.pem_certificate_chain == ["pem_certificate_chain_value"] - assert response.instance_uid == "instance_uid_value" + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_get_connection_info_rest_required_fields( - request_type=service.GetConnectionInfoRequest, -): +def test_list_users_rest_required_fields(request_type=service.ListUsersRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} @@ -17692,7 +18554,7 @@ def test_get_connection_info_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_connection_info._get_unset_required_fields(jsonified_request) + ).list_users._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -17701,9 +18563,16 @@ def test_get_connection_info_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_connection_info._get_unset_required_fields(jsonified_request) + ).list_users._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + 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 @@ -17717,7 +18586,7 @@ def test_get_connection_info_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.ConnectionInfo() + return_value = service.ListUsersResponse() # 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 @@ -17738,30 +18607,40 @@ def test_get_connection_info_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.ConnectionInfo.pb(return_value) + return_value = service.ListUsersResponse.pb(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_connection_info(request) + response = client.list_users(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_connection_info_rest_unset_required_fields(): +def test_list_users_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_connection_info._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId",)) & set(("parent",))) + unset_fields = transport.list_users._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_connection_info_rest_interceptors(null_interceptor): +def test_list_users_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -17774,15 +18653,13 @@ def test_get_connection_info_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_get_connection_info" + transports.AlloyDBAdminRestInterceptor, "post_list_users" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_get_connection_info" + transports.AlloyDBAdminRestInterceptor, "pre_list_users" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.GetConnectionInfoRequest.pb( - service.GetConnectionInfoRequest() - ) + pb_message = service.ListUsersRequest.pb(service.ListUsersRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -17793,19 +18670,19 @@ def test_get_connection_info_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.ConnectionInfo.to_json( - resources.ConnectionInfo() + req.return_value._content = service.ListUsersResponse.to_json( + service.ListUsersResponse() ) - request = service.GetConnectionInfoRequest() + request = service.ListUsersRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.ConnectionInfo() + post.return_value = service.ListUsersResponse() - client.get_connection_info( + client.list_users( request, metadata=[ ("key", "val"), @@ -17817,8 +18694,8 @@ def test_get_connection_info_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_connection_info_rest_bad_request( - transport: str = "rest", request_type=service.GetConnectionInfoRequest +def test_list_users_rest_bad_request( + transport: str = "rest", request_type=service.ListUsersRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -17826,9 +18703,7 @@ def test_get_connection_info_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -17840,10 +18715,10 @@ def test_get_connection_info_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_connection_info(request) + client.list_users(request) -def test_get_connection_info_rest_flattened(): +def test_list_users_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -17852,11 +18727,11 @@ def test_get_connection_info_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 = resources.ConnectionInfo() + return_value = service.ListUsersResponse() # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + "parent": "projects/sample1/locations/sample2/clusters/sample3" } # get truthy value for each flattened field @@ -17869,25 +18744,25 @@ def test_get_connection_info_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.ConnectionInfo.pb(return_value) + return_value = service.ListUsersResponse.pb(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_connection_info(**mock_args) + client.list_users(**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/*/clusters/*/instances/*}/connectionInfo" + "%s/v1beta/{parent=projects/*/locations/*/clusters/*}/users" % client.transport._host, args[1], ) -def test_get_connection_info_rest_flattened_error(transport: str = "rest"): +def test_list_users_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17896,65 +18771,128 @@ def test_get_connection_info_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.get_connection_info( - service.GetConnectionInfoRequest(), + client.list_users( + service.ListUsersRequest(), parent="parent_value", ) -def test_get_connection_info_rest_error(): +def test_list_users_rest_pager(transport: str = "rest"): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token="abc", + ), + service.ListUsersResponse( + users=[], + next_page_token="def", + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token="ghi", + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListUsersResponse.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/clusters/sample3" + } + + pager = client.list_users(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.User) for i in results) + + pages = list(client.list_users(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - service.ListUsersRequest, + service.GetUserRequest, dict, ], ) -def test_list_users_rest(request_type): +def test_get_user_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/clusters/sample3/users/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 = service.ListUsersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + return_value = resources.User( + name="name_value", + password="password_value", + database_roles=["database_roles_value"], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListUsersResponse.pb(return_value) + return_value = resources.User.pb(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_users(request) + response = client.get_user(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsersPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, resources.User) + assert response.name == "name_value" + assert response.password == "password_value" + assert response.database_roles == ["database_roles_value"] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN -def test_list_users_rest_required_fields(request_type=service.ListUsersRequest): +def test_get_user_rest_required_fields(request_type=service.GetUserRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -17965,30 +18903,21 @@ def test_list_users_rest_required_fields(request_type=service.ListUsersRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_users._get_unset_required_fields(jsonified_request) + ).get_user._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" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_users._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", - ) - ) + ).get_user._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" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -17997,7 +18926,7 @@ def test_list_users_rest_required_fields(request_type=service.ListUsersRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListUsersResponse() + return_value = resources.User() # 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 @@ -18018,40 +18947,30 @@ def test_list_users_rest_required_fields(request_type=service.ListUsersRequest): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListUsersResponse.pb(return_value) + return_value = resources.User.pb(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_users(request) + response = client.get_user(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_users_rest_unset_required_fields(): +def test_get_user_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_users._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.get_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_users_rest_interceptors(null_interceptor): +def test_get_user_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -18064,13 +18983,13 @@ def test_list_users_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_list_users" + transports.AlloyDBAdminRestInterceptor, "post_get_user" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_list_users" + transports.AlloyDBAdminRestInterceptor, "pre_get_user" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListUsersRequest.pb(service.ListUsersRequest()) + pb_message = service.GetUserRequest.pb(service.GetUserRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -18081,19 +19000,17 @@ def test_list_users_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = service.ListUsersResponse.to_json( - service.ListUsersResponse() - ) + req.return_value._content = resources.User.to_json(resources.User()) - request = service.ListUsersRequest() + request = service.GetUserRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListUsersResponse() + post.return_value = resources.User() - client.list_users( + client.get_user( request, metadata=[ ("key", "val"), @@ -18105,8 +19022,8 @@ def test_list_users_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_users_rest_bad_request( - transport: str = "rest", request_type=service.ListUsersRequest +def test_get_user_rest_bad_request( + transport: str = "rest", request_type=service.GetUserRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18114,7 +19031,9 @@ def test_list_users_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -18126,10 +19045,10 @@ def test_list_users_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_users(request) + client.get_user(request) -def test_list_users_rest_flattened(): +def test_get_user_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18138,16 +19057,16 @@ def test_list_users_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 = service.ListUsersResponse() + return_value = resources.User() # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/clusters/sample3" + "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) @@ -18155,25 +19074,25 @@ def test_list_users_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListUsersResponse.pb(return_value) + return_value = resources.User.pb(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_users(**mock_args) + client.get_user(**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/*/clusters/*}/users" + "%s/v1beta/{name=projects/*/locations/*/clusters/*/users/*}" % client.transport._host, args[1], ) -def test_list_users_rest_flattened_error(transport: str = "rest"): +def test_get_user_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18182,92 +19101,106 @@ def test_list_users_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.list_users( - service.ListUsersRequest(), - parent="parent_value", + client.get_user( + service.GetUserRequest(), + name="name_value", ) -def test_list_users_rest_pager(transport: str = "rest"): +def test_get_user_rest_error(): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), 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 = ( - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - resources.User(), - ], - next_page_token="abc", - ), - service.ListUsersResponse( - users=[], - next_page_token="def", - ), - service.ListUsersResponse( - users=[ - resources.User(), - ], - next_page_token="ghi", - ), - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListUsersResponse.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/clusters/sample3" - } - - pager = client.list_users(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.User) for i in results) - - pages = list(client.list_users(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - service.GetUserRequest, + service.CreateUserRequest, dict, ], ) -def test_get_user_rest(request_type): +def test_create_user_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init["user"] = { + "name": "name_value", + "password": "password_value", + "database_roles": ["database_roles_value1", "database_roles_value2"], + "user_type": 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 = service.CreateUserRequest.meta.fields["user"] + + 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["user"].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["user"][field])): + del request_init["user"][field][i][subfield] + else: + del request_init["user"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -18289,7 +19222,7 @@ def test_get_user_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_user(request) + response = client.create_user(request) # Establish that the response is the type that we expect. assert isinstance(response, resources.User) @@ -18299,11 +19232,12 @@ def test_get_user_rest(request_type): assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN -def test_get_user_rest_required_fields(request_type=service.GetUserRequest): +def test_create_user_rest_required_fields(request_type=service.CreateUserRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["user_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -18311,24 +19245,38 @@ def test_get_user_rest_required_fields(request_type=service.GetUserRequest): ) # verify fields with default values are dropped + assert "userId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_user._get_unset_required_fields(jsonified_request) + ).create_user._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "userId" in jsonified_request + assert jsonified_request["userId"] == request_init["user_id"] - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["userId"] = "user_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_user._get_unset_required_fields(jsonified_request) + ).create_user._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "user_id", + "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 "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "userId" in jsonified_request + assert jsonified_request["userId"] == "user_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18349,9 +19297,10 @@ def test_get_user_rest_required_fields(request_type=service.GetUserRequest): 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() @@ -18364,24 +19313,45 @@ def test_get_user_rest_required_fields(request_type=service.GetUserRequest): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_user(request) + response = client.create_user(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "userId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_user_rest_unset_required_fields(): +def test_create_user_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_user._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_user._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "userId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "userId", + "user", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_user_rest_interceptors(null_interceptor): +def test_create_user_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -18394,13 +19364,13 @@ def test_get_user_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_get_user" + transports.AlloyDBAdminRestInterceptor, "post_create_user" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_get_user" + transports.AlloyDBAdminRestInterceptor, "pre_create_user" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.GetUserRequest.pb(service.GetUserRequest()) + pb_message = service.CreateUserRequest.pb(service.CreateUserRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -18413,7 +19383,7 @@ def test_get_user_rest_interceptors(null_interceptor): req.return_value.request = PreparedRequest() req.return_value._content = resources.User.to_json(resources.User()) - request = service.GetUserRequest() + request = service.CreateUserRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -18421,7 +19391,7 @@ def test_get_user_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = resources.User() - client.get_user( + client.create_user( request, metadata=[ ("key", "val"), @@ -18433,8 +19403,8 @@ def test_get_user_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_user_rest_bad_request( - transport: str = "rest", request_type=service.GetUserRequest +def test_create_user_rest_bad_request( + transport: str = "rest", request_type=service.CreateUserRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18442,9 +19412,7 @@ def test_get_user_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" - } + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -18456,10 +19424,10 @@ def test_get_user_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_user(request) + client.create_user(request) -def test_get_user_rest_flattened(): +def test_create_user_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18472,12 +19440,14 @@ def test_get_user_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" + "parent": "projects/sample1/locations/sample2/clusters/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + user=resources.User(name="name_value"), + user_id="user_id_value", ) mock_args.update(sample_request) @@ -18490,20 +19460,20 @@ def test_get_user_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_user(**mock_args) + client.create_user(**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/*/clusters/*/users/*}" + "%s/v1beta/{parent=projects/*/locations/*/clusters/*}/users" % client.transport._host, args[1], ) -def test_get_user_rest_flattened_error(transport: str = "rest"): +def test_create_user_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18512,13 +19482,15 @@ def test_get_user_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.get_user( - service.GetUserRequest(), - name="name_value", + client.create_user( + service.CreateUserRequest(), + parent="parent_value", + user=resources.User(name="name_value"), + user_id="user_id_value", ) -def test_get_user_rest_error(): +def test_create_user_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -18527,20 +19499,24 @@ def test_get_user_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.CreateUserRequest, + service.UpdateUserRequest, dict, ], ) -def test_create_user_rest(request_type): +def test_update_user_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = { + "user": { + "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" + } + } request_init["user"] = { - "name": "name_value", + "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4", "password": "password_value", "database_roles": ["database_roles_value1", "database_roles_value2"], "user_type": 1, @@ -18550,7 +19526,7 @@ def test_create_user_rest(request_type): # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = service.CreateUserRequest.meta.fields["user"] + test_field = service.UpdateUserRequest.meta.fields["user"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -18633,7 +19609,7 @@ def get_message_fields(field): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_user(request) + response = client.update_user(request) # Establish that the response is the type that we expect. assert isinstance(response, resources.User) @@ -18643,12 +19619,10 @@ def get_message_fields(field): assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN -def test_create_user_rest_required_fields(request_type=service.CreateUserRequest): +def test_update_user_rest_required_fields(request_type=service.UpdateUserRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" - request_init["user_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -18656,38 +19630,29 @@ def test_create_user_rest_required_fields(request_type=service.CreateUserRequest ) # verify fields with default values are dropped - assert "userId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_user._get_unset_required_fields(jsonified_request) + ).update_user._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "userId" in jsonified_request - assert jsonified_request["userId"] == request_init["user_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["userId"] = "user_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_user._get_unset_required_fields(jsonified_request) + ).update_user._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", "request_id", - "user_id", + "update_mask", "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 "userId" in jsonified_request - assert jsonified_request["userId"] == "user_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18708,7 +19673,7 @@ def test_create_user_rest_required_fields(request_type=service.CreateUserRequest 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 @@ -18724,45 +19689,34 @@ def test_create_user_rest_required_fields(request_type=service.CreateUserRequest response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_user(request) + response = client.update_user(request) - expected_params = [ - ( - "userId", - "", - ), - ("$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_create_user_rest_unset_required_fields(): +def test_update_user_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_user._get_unset_required_fields({}) + unset_fields = transport.update_user._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( + "allowMissing", "requestId", - "userId", + "updateMask", "validateOnly", ) ) - & set( - ( - "parent", - "userId", - "user", - ) - ) + & set(("user",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_user_rest_interceptors(null_interceptor): +def test_update_user_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -18775,13 +19729,13 @@ def test_create_user_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_create_user" + transports.AlloyDBAdminRestInterceptor, "post_update_user" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_create_user" + transports.AlloyDBAdminRestInterceptor, "pre_update_user" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.CreateUserRequest.pb(service.CreateUserRequest()) + pb_message = service.UpdateUserRequest.pb(service.UpdateUserRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -18794,7 +19748,7 @@ def test_create_user_rest_interceptors(null_interceptor): req.return_value.request = PreparedRequest() req.return_value._content = resources.User.to_json(resources.User()) - request = service.CreateUserRequest() + request = service.UpdateUserRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -18802,7 +19756,7 @@ def test_create_user_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = resources.User() - client.create_user( + client.update_user( request, metadata=[ ("key", "val"), @@ -18814,8 +19768,8 @@ def test_create_user_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_user_rest_bad_request( - transport: str = "rest", request_type=service.CreateUserRequest +def test_update_user_rest_bad_request( + transport: str = "rest", request_type=service.UpdateUserRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18823,7 +19777,11 @@ def test_create_user_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = { + "user": { + "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" + } + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -18835,10 +19793,10 @@ def test_create_user_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_user(request) + client.update_user(request) -def test_create_user_rest_flattened(): +def test_update_user_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18851,14 +19809,15 @@ def test_create_user_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/clusters/sample3" + "user": { + "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" + } } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", user=resources.User(name="name_value"), - user_id="user_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -18871,20 +19830,20 @@ def test_create_user_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_user(**mock_args) + client.update_user(**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/*/clusters/*}/users" + "%s/v1beta/{user.name=projects/*/locations/*/clusters/*/users/*}" % client.transport._host, args[1], ) -def test_create_user_rest_flattened_error(transport: str = "rest"): +def test_update_user_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18893,15 +19852,14 @@ def test_create_user_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.create_user( - service.CreateUserRequest(), - parent="parent_value", + client.update_user( + service.UpdateUserRequest(), user=resources.User(name="name_value"), - user_id="user_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_create_user_rest_error(): +def test_update_user_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -18910,11 +19868,11 @@ def test_create_user_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.UpdateUserRequest, + service.DeleteUserRequest, dict, ], ) -def test_update_user_rest(request_type): +def test_delete_user_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18922,118 +19880,33 @@ def test_update_user_rest(request_type): # send a request that will satisfy transcoding request_init = { - "user": { - "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" - } - } - request_init["user"] = { - "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4", - "password": "password_value", - "database_roles": ["database_roles_value1", "database_roles_value2"], - "user_type": 1, + "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" } - # 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 = service.UpdateUserRequest.meta.fields["user"] - - 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["user"].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["user"][field])): - del request_init["user"][field][i][subfield] - else: - del request_init["user"][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 = resources.User( - name="name_value", - password="password_value", - database_roles=["database_roles_value"], - user_type=resources.User.UserType.ALLOYDB_BUILT_IN, - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.User.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_user(request) + response = client.delete_user(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.User) - assert response.name == "name_value" - assert response.password == "password_value" - assert response.database_roles == ["database_roles_value"] - assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + assert response is None -def test_update_user_rest_required_fields(request_type=service.UpdateUserRequest): +def test_delete_user_rest_required_fields(request_type=service.DeleteUserRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -19044,26 +19917,28 @@ def test_update_user_rest_required_fields(request_type=service.UpdateUserRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_user._get_unset_required_fields(jsonified_request) + ).delete_user._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_user._get_unset_required_fields(jsonified_request) + ).delete_user._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", "request_id", - "update_mask", "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 = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19072,7 +19947,7 @@ def test_update_user_rest_required_fields(request_type=service.UpdateUserRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.User() + return_value = None # 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 @@ -19084,50 +19959,44 @@ def test_update_user_rest_required_fields(request_type=service.UpdateUserRequest pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "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 = resources.User.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_user(request) + response = client.delete_user(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_user_rest_unset_required_fields(): +def test_delete_user_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_user._get_unset_required_fields({}) + unset_fields = transport.delete_user._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "allowMissing", "requestId", - "updateMask", "validateOnly", ) ) - & set(("user",)) + & set(("name",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_user_rest_interceptors(null_interceptor): +def test_delete_user_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19140,13 +20009,10 @@ def test_update_user_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_update_user" - ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_update_user" + transports.AlloyDBAdminRestInterceptor, "pre_delete_user" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = service.UpdateUserRequest.pb(service.UpdateUserRequest()) + pb_message = service.DeleteUserRequest.pb(service.DeleteUserRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -19157,17 +20023,15 @@ def test_update_user_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.User.to_json(resources.User()) - request = service.UpdateUserRequest() + request = service.DeleteUserRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.User() - client.update_user( + client.delete_user( request, metadata=[ ("key", "val"), @@ -19176,11 +20040,10 @@ def test_update_user_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_update_user_rest_bad_request( - transport: str = "rest", request_type=service.UpdateUserRequest +def test_delete_user_rest_bad_request( + transport: str = "rest", request_type=service.DeleteUserRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19189,9 +20052,7 @@ def test_update_user_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "user": { - "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" - } + "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" } request = request_type(**request_init) @@ -19204,10 +20065,10 @@ def test_update_user_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_user(request) + client.delete_user(request) -def test_update_user_rest_flattened(): +def test_delete_user_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -19216,45 +20077,40 @@ def test_update_user_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 = resources.User() + return_value = None # get arguments that satisfy an http rule for this method sample_request = { - "user": { - "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" - } + "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" } # get truthy value for each flattened field mock_args = dict( - user=resources.User(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = resources.User.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 - client.update_user(**mock_args) + client.delete_user(**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/{user.name=projects/*/locations/*/clusters/*/users/*}" + "%s/v1beta/{name=projects/*/locations/*/clusters/*/users/*}" % client.transport._host, args[1], ) -def test_update_user_rest_flattened_error(transport: str = "rest"): +def test_delete_user_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19263,14 +20119,13 @@ def test_update_user_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_user( - service.UpdateUserRequest(), - user=resources.User(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_user( + service.DeleteUserRequest(), + name="name_value", ) -def test_update_user_rest_error(): +def test_delete_user_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -19279,45 +20134,48 @@ def test_update_user_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.DeleteUserRequest, + service.ListDatabasesRequest, dict, ], ) -def test_delete_user_rest(request_type): +def test_list_databases_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" - } + request_init = {"parent": "projects/sample1/locations/sample2/clusters/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 = None + return_value = service.ListDatabasesResponse( + next_page_token="next_page_token_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = service.ListDatabasesResponse.pb(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.delete_user(request) + response = client.list_databases(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, pagers.ListDatabasesPager) + assert response.next_page_token == "next_page_token_value" -def test_delete_user_rest_required_fields(request_type=service.DeleteUserRequest): +def test_list_databases_rest_required_fields(request_type=service.ListDatabasesRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -19328,28 +20186,29 @@ def test_delete_user_rest_required_fields(request_type=service.DeleteUserRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_user._get_unset_required_fields(jsonified_request) + ).list_databases._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_user._get_unset_required_fields(jsonified_request) + ).list_databases._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "request_id", - "validate_only", + "filter", + "page_size", + "page_token", ) ) 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 = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19358,7 +20217,7 @@ def test_delete_user_rest_required_fields(request_type=service.DeleteUserRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = service.ListDatabasesResponse() # 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 @@ -19370,44 +20229,48 @@ def test_delete_user_rest_required_fields(request_type=service.DeleteUserRequest pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "get", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = service.ListDatabasesResponse.pb(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.delete_user(request) + response = client.list_databases(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_user_rest_unset_required_fields(): +def test_list_databases_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_user._get_unset_required_fields({}) + unset_fields = transport.list_databases._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "requestId", - "validateOnly", + "filter", + "pageSize", + "pageToken", ) ) - & set(("name",)) + & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_user_rest_interceptors(null_interceptor): +def test_list_databases_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19420,10 +20283,13 @@ def test_delete_user_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_delete_user" + transports.AlloyDBAdminRestInterceptor, "post_list_databases" + ) as post, mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "pre_list_databases" ) as pre: pre.assert_not_called() - pb_message = service.DeleteUserRequest.pb(service.DeleteUserRequest()) + post.assert_not_called() + pb_message = service.ListDatabasesRequest.pb(service.ListDatabasesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -19434,15 +20300,19 @@ def test_delete_user_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = service.ListDatabasesResponse.to_json( + service.ListDatabasesResponse() + ) - request = service.DeleteUserRequest() + request = service.ListDatabasesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = service.ListDatabasesResponse() - client.delete_user( + client.list_databases( request, metadata=[ ("key", "val"), @@ -19451,10 +20321,11 @@ def test_delete_user_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_delete_user_rest_bad_request( - transport: str = "rest", request_type=service.DeleteUserRequest +def test_list_databases_rest_bad_request( + transport: str = "rest", request_type=service.ListDatabasesRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19462,9 +20333,7 @@ def test_delete_user_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" - } + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -19476,10 +20345,10 @@ def test_delete_user_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_user(request) + client.list_databases(request) -def test_delete_user_rest_flattened(): +def test_list_databases_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -19488,40 +20357,42 @@ def test_delete_user_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 = None + return_value = service.ListDatabasesResponse() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" + "parent": "projects/sample1/locations/sample2/clusters/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + 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 = "" + # Convert return value to protobuf type + return_value = service.ListDatabasesResponse.pb(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.delete_user(**mock_args) + client.list_databases(**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/*/clusters/*/users/*}" + "%s/v1beta/{parent=projects/*/locations/*/clusters/*}/databases" % client.transport._host, args[1], ) -def test_delete_user_rest_flattened_error(transport: str = "rest"): +def test_list_databases_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19530,17 +20401,74 @@ def test_delete_user_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_user( - service.DeleteUserRequest(), - name="name_value", + client.list_databases( + service.ListDatabasesRequest(), + parent="parent_value", ) -def test_delete_user_rest_error(): +def test_list_databases_rest_pager(transport: str = "rest"): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + resources.Database(), + ], + next_page_token="abc", + ), + service.ListDatabasesResponse( + databases=[], + next_page_token="def", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + ], + next_page_token="ghi", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListDatabasesResponse.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/clusters/sample3" + } + + pager = client.list_databases(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Database) for i in results) + + pages = list(client.list_databases(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. @@ -19712,6 +20640,7 @@ def test_alloy_db_admin_base_transport(): "create_user", "update_user", "delete_user", + "list_databases", "get_location", "list_locations", "get_operation", @@ -20088,6 +21017,9 @@ def test_alloy_db_admin_client_transport_session_collision(transport_name): session1 = client1.transport.delete_user._session session2 = client2.transport.delete_user._session assert session1 != session2 + session1 = client1.transport.list_databases._session + session2 = client2.transport.list_databases._session + assert session1 != session2 def test_alloy_db_admin_grpc_transport_channel(): @@ -20359,11 +21291,40 @@ def test_parse_crypto_key_version_path(): assert expected == actual -def test_instance_path(): +def test_database_path(): project = "cuttlefish" location = "mussel" cluster = "winkle" - instance = "nautilus" + database = "nautilus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/databases/{database}".format( + project=project, + location=location, + cluster=cluster, + database=database, + ) + actual = AlloyDBAdminClient.database_path(project, location, cluster, database) + assert expected == actual + + +def test_parse_database_path(): + expected = { + "project": "scallop", + "location": "abalone", + "cluster": "squid", + "database": "clam", + } + path = AlloyDBAdminClient.database_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_database_path(path) + assert expected == actual + + +def test_instance_path(): + project = "whelk" + location = "octopus" + cluster = "oyster" + instance = "nudibranch" expected = "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}".format( project=project, location=location, @@ -20376,10 +21337,10 @@ def test_instance_path(): def test_parse_instance_path(): expected = { - "project": "scallop", - "location": "abalone", - "cluster": "squid", - "instance": "clam", + "project": "cuttlefish", + "location": "mussel", + "cluster": "winkle", + "instance": "nautilus", } path = AlloyDBAdminClient.instance_path(**expected) @@ -20389,8 +21350,8 @@ def test_parse_instance_path(): def test_network_path(): - project = "whelk" - network = "octopus" + project = "scallop" + network = "abalone" expected = "projects/{project}/global/networks/{network}".format( project=project, network=network, @@ -20401,8 +21362,8 @@ def test_network_path(): def test_parse_network_path(): expected = { - "project": "oyster", - "network": "nudibranch", + "project": "squid", + "network": "clam", } path = AlloyDBAdminClient.network_path(**expected) @@ -20412,9 +21373,9 @@ def test_parse_network_path(): def test_supported_database_flag_path(): - project = "cuttlefish" - location = "mussel" - flag = "winkle" + project = "whelk" + location = "octopus" + flag = "oyster" expected = "projects/{project}/locations/{location}/flags/{flag}".format( project=project, location=location, @@ -20426,9 +21387,9 @@ def test_supported_database_flag_path(): def test_parse_supported_database_flag_path(): expected = { - "project": "nautilus", - "location": "scallop", - "flag": "abalone", + "project": "nudibranch", + "location": "cuttlefish", + "flag": "mussel", } path = AlloyDBAdminClient.supported_database_flag_path(**expected) @@ -20438,10 +21399,10 @@ def test_parse_supported_database_flag_path(): def test_user_path(): - project = "squid" - location = "clam" - cluster = "whelk" - user = "octopus" + project = "winkle" + location = "nautilus" + cluster = "scallop" + user = "abalone" expected = "projects/{project}/locations/{location}/clusters/{cluster}/users/{user}".format( project=project, location=location, @@ -20454,10 +21415,10 @@ def test_user_path(): def test_parse_user_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "cluster": "cuttlefish", - "user": "mussel", + "project": "squid", + "location": "clam", + "cluster": "whelk", + "user": "octopus", } path = AlloyDBAdminClient.user_path(**expected) @@ -20467,7 +21428,7 @@ def test_parse_user_path(): def test_common_billing_account_path(): - billing_account = "winkle" + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -20477,7 +21438,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nautilus", + "billing_account": "nudibranch", } path = AlloyDBAdminClient.common_billing_account_path(**expected) @@ -20487,7 +21448,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "scallop" + folder = "cuttlefish" expected = "folders/{folder}".format( folder=folder, ) @@ -20497,7 +21458,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "abalone", + "folder": "mussel", } path = AlloyDBAdminClient.common_folder_path(**expected) @@ -20507,7 +21468,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "squid" + organization = "winkle" expected = "organizations/{organization}".format( organization=organization, ) @@ -20517,7 +21478,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "clam", + "organization": "nautilus", } path = AlloyDBAdminClient.common_organization_path(**expected) @@ -20527,7 +21488,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "whelk" + project = "scallop" expected = "projects/{project}".format( project=project, ) @@ -20537,7 +21498,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "octopus", + "project": "abalone", } path = AlloyDBAdminClient.common_project_path(**expected) @@ -20547,8 +21508,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "oyster" - location = "nudibranch" + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -20559,8 +21520,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "cuttlefish", - "location": "mussel", + "project": "whelk", + "location": "octopus", } path = AlloyDBAdminClient.common_location_path(**expected) diff --git a/packages/google-cloud-api-gateway/CHANGELOG.md b/packages/google-cloud-api-gateway/CHANGELOG.md index c929277bc110..1b5597276958 100644 --- a/packages/google-cloud-api-gateway/CHANGELOG.md +++ b/packages/google-cloud-api-gateway/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.9.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-api-gateway-v1.9.2...google-cloud-api-gateway-v1.9.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [1.9.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-api-gateway-v1.9.1...google-cloud-api-gateway-v1.9.2) (2024-02-22) 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 f14078b6f555..ec42a8e289c4 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.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {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 f14078b6f555..ec42a8e289c4 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.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} 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 5bebd5de6df8..06bde62ec8c6 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.9.2" + "version": "1.9.3" }, "snippets": [ { diff --git a/packages/google-cloud-api-gateway/setup.py b/packages/google-cloud-api-gateway/setup.py index 94102c2484c0..0b84088689d3 100644 --- a/packages/google-cloud-api-gateway/setup.py +++ b/packages/google-cloud-api-gateway/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-api-keys/CHANGELOG.md b/packages/google-cloud-api-keys/CHANGELOG.md index aacb3d92c6fa..2cf2ddc0f0d4 100644 --- a/packages/google-cloud-api-keys/CHANGELOG.md +++ b/packages/google-cloud-api-keys/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.5.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-api-keys-v0.5.8...google-cloud-api-keys-v0.5.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [0.5.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-api-keys-v0.5.7...google-cloud-api-keys-v0.5.8) (2024-02-22) 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 09f1bfa9ad82..f4186fc1a151 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.8" # {x-release-please-version} +__version__ = "0.5.9" # {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 09f1bfa9ad82..f4186fc1a151 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.8" # {x-release-please-version} +__version__ = "0.5.9" # {x-release-please-version} 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 d7bfbfab1f9e..b2fb91a9ff45 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.8" + "version": "0.5.9" }, "snippets": [ { diff --git a/packages/google-cloud-api-keys/setup.py b/packages/google-cloud-api-keys/setup.py index b1bda06ef5cd..2ef4793f4e0d 100644 --- a/packages/google-cloud-api-keys/setup.py +++ b/packages/google-cloud-api-keys/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-apigee-connect/CHANGELOG.md b/packages/google-cloud-apigee-connect/CHANGELOG.md index c3c02e6ef866..9673c4517f5f 100644 --- a/packages/google-cloud-apigee-connect/CHANGELOG.md +++ b/packages/google-cloud-apigee-connect/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.9.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-apigee-connect-v1.9.2...google-cloud-apigee-connect-v1.9.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [1.9.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-apigee-connect-v1.9.1...google-cloud-apigee-connect-v1.9.2) (2024-02-22) 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 f14078b6f555..ec42a8e289c4 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.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {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 f14078b6f555..ec42a8e289c4 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.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} 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 28ae7739969c..bcef129c32c3 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.9.2" + "version": "1.9.3" }, "snippets": [ { diff --git a/packages/google-cloud-apigee-connect/setup.py b/packages/google-cloud-apigee-connect/setup.py index df6c5537f3c1..02ce180b0a77 100644 --- a/packages/google-cloud-apigee-connect/setup.py +++ b/packages/google-cloud-apigee-connect/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-apigee-registry/CHANGELOG.md b/packages/google-cloud-apigee-registry/CHANGELOG.md index 4a6e4dd4a702..7062209a27f3 100644 --- a/packages/google-cloud-apigee-registry/CHANGELOG.md +++ b/packages/google-cloud-apigee-registry/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.6.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-apigee-registry-v0.6.8...google-cloud-apigee-registry-v0.6.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [0.6.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-apigee-registry-v0.6.7...google-cloud-apigee-registry-v0.6.8) (2024-02-22) 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 93768f73f8ae..5106807e66a2 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.8" # {x-release-please-version} +__version__ = "0.6.9" # {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 93768f73f8ae..5106807e66a2 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.8" # {x-release-please-version} +__version__ = "0.6.9" # {x-release-please-version} 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 31d9066e823c..6c29560b5389 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.8" + "version": "0.6.9" }, "snippets": [ { diff --git a/packages/google-cloud-apigee-registry/setup.py b/packages/google-cloud-apigee-registry/setup.py index 40a57a82b3df..267ec3840a70 100644 --- a/packages/google-cloud-apigee-registry/setup.py +++ b/packages/google-cloud-apigee-registry/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-appengine-admin/CHANGELOG.md b/packages/google-cloud-appengine-admin/CHANGELOG.md index 9c08e5706741..4079143e08b3 100644 --- a/packages/google-cloud-appengine-admin/CHANGELOG.md +++ b/packages/google-cloud-appengine-admin/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.11.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-appengine-admin-v1.11.2...google-cloud-appengine-admin-v1.11.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [1.11.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-appengine-admin-v1.11.1...google-cloud-appengine-admin-v1.11.2) (2024-02-22) 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 787a045996f3..88fbabfeb794 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.11.2" # {x-release-please-version} +__version__ = "1.11.3" # {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 787a045996f3..88fbabfeb794 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.11.2" # {x-release-please-version} +__version__ = "1.11.3" # {x-release-please-version} 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 3353b99df781..bc87025fdeb3 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.11.2" + "version": "1.11.3" }, "snippets": [ { diff --git a/packages/google-cloud-appengine-admin/setup.py b/packages/google-cloud-appengine-admin/setup.py index 3dfec348f43c..7a8f797a493c 100644 --- a/packages/google-cloud-appengine-admin/setup.py +++ b/packages/google-cloud-appengine-admin/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-appengine-logging/CHANGELOG.md b/packages/google-cloud-appengine-logging/CHANGELOG.md index 371557ccc380..2621e7592f00 100644 --- a/packages/google-cloud-appengine-logging/CHANGELOG.md +++ b/packages/google-cloud-appengine-logging/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.4.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-appengine-logging-v1.4.2...google-cloud-appengine-logging-v1.4.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [1.4.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-appengine-logging-v1.4.1...google-cloud-appengine-logging-v1.4.2) (2024-02-22) diff --git a/packages/google-cloud-appengine-logging/google/cloud/appengine_logging/gapic_version.py b/packages/google-cloud-appengine-logging/google/cloud/appengine_logging/gapic_version.py index 51f58966561e..4f9b5347cdbf 100644 --- a/packages/google-cloud-appengine-logging/google/cloud/appengine_logging/gapic_version.py +++ b/packages/google-cloud-appengine-logging/google/cloud/appengine_logging/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.4.2" # {x-release-please-version} +__version__ = "1.4.3" # {x-release-please-version} diff --git a/packages/google-cloud-appengine-logging/google/cloud/appengine_logging_v1/gapic_version.py b/packages/google-cloud-appengine-logging/google/cloud/appengine_logging_v1/gapic_version.py index 51f58966561e..4f9b5347cdbf 100644 --- a/packages/google-cloud-appengine-logging/google/cloud/appengine_logging_v1/gapic_version.py +++ b/packages/google-cloud-appengine-logging/google/cloud/appengine_logging_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.4.2" # {x-release-please-version} +__version__ = "1.4.3" # {x-release-please-version} diff --git a/packages/google-cloud-appengine-logging/setup.py b/packages/google-cloud-appengine-logging/setup.py index c4f565ada175..c4902afce68d 100644 --- a/packages/google-cloud-appengine-logging/setup.py +++ b/packages/google-cloud-appengine-logging/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-artifact-registry/CHANGELOG.md b/packages/google-cloud-artifact-registry/CHANGELOG.md index fe8082c8285d..2518fdf127b7 100644 --- a/packages/google-cloud-artifact-registry/CHANGELOG.md +++ b/packages/google-cloud-artifact-registry/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.11.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-artifact-registry-v1.11.2...google-cloud-artifact-registry-v1.11.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [1.11.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-artifact-registry-v1.11.1...google-cloud-artifact-registry-v1.11.2) (2024-02-22) diff --git a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry/gapic_version.py b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry/gapic_version.py index 787a045996f3..88fbabfeb794 100644 --- a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry/gapic_version.py +++ b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.11.2" # {x-release-please-version} +__version__ = "1.11.3" # {x-release-please-version} diff --git a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/gapic_version.py b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/gapic_version.py index 787a045996f3..88fbabfeb794 100644 --- a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/gapic_version.py +++ b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_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.2" # {x-release-please-version} +__version__ = "1.11.3" # {x-release-please-version} diff --git a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1beta2/gapic_version.py b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1beta2/gapic_version.py index 787a045996f3..88fbabfeb794 100644 --- a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1beta2/gapic_version.py +++ b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1beta2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.11.2" # {x-release-please-version} +__version__ = "1.11.3" # {x-release-please-version} diff --git a/packages/google-cloud-artifact-registry/samples/generated_samples/snippet_metadata_google.devtools.artifactregistry.v1.json b/packages/google-cloud-artifact-registry/samples/generated_samples/snippet_metadata_google.devtools.artifactregistry.v1.json index b99c5bdc98fc..773c1b066925 100644 --- a/packages/google-cloud-artifact-registry/samples/generated_samples/snippet_metadata_google.devtools.artifactregistry.v1.json +++ b/packages/google-cloud-artifact-registry/samples/generated_samples/snippet_metadata_google.devtools.artifactregistry.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-artifact-registry", - "version": "1.11.2" + "version": "1.11.3" }, "snippets": [ { diff --git a/packages/google-cloud-artifact-registry/samples/generated_samples/snippet_metadata_google.devtools.artifactregistry.v1beta2.json b/packages/google-cloud-artifact-registry/samples/generated_samples/snippet_metadata_google.devtools.artifactregistry.v1beta2.json index 18bf57320c60..af527b5bf049 100644 --- a/packages/google-cloud-artifact-registry/samples/generated_samples/snippet_metadata_google.devtools.artifactregistry.v1beta2.json +++ b/packages/google-cloud-artifact-registry/samples/generated_samples/snippet_metadata_google.devtools.artifactregistry.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-artifact-registry", - "version": "1.11.2" + "version": "1.11.3" }, "snippets": [ { diff --git a/packages/google-cloud-artifact-registry/setup.py b/packages/google-cloud-artifact-registry/setup.py index ce9b6085402e..c32610339ee8 100644 --- a/packages/google-cloud-artifact-registry/setup.py +++ b/packages/google-cloud-artifact-registry/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-asset/CHANGELOG.md b/packages/google-cloud-asset/CHANGELOG.md index ec871da2dffa..d6cf030307d0 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.24.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-asset-v3.24.2...google-cloud-asset-v3.24.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [3.24.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-asset-v3.24.1...google-cloud-asset-v3.24.2) (2024-02-22) 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 c61168959fd7..17721205f5d2 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.24.2" # {x-release-please-version} +__version__ = "3.24.3" # {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 c61168959fd7..17721205f5d2 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.24.2" # {x-release-please-version} +__version__ = "3.24.3" # {x-release-please-version} 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 c61168959fd7..17721205f5d2 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.24.2" # {x-release-please-version} +__version__ = "3.24.3" # {x-release-please-version} 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 c61168959fd7..17721205f5d2 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.24.2" # {x-release-please-version} +__version__ = "3.24.3" # {x-release-please-version} 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 24eac60908bf..5829d2742788 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.24.2" # {x-release-please-version} +__version__ = "3.24.3" # {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 c61168959fd7..17721205f5d2 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.24.2" # {x-release-please-version} +__version__ = "3.24.3" # {x-release-please-version} 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 dc1b767b7424..f0da0b7583e5 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.24.2" + "version": "3.24.3" }, "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 86ab756d8492..aa9c10175ef8 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.24.2" + "version": "3.24.3" }, "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 c0398c3e81f5..d04c7736459a 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.24.2" + "version": "3.24.3" }, "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 aa3578edb3f4..0939bf6b7954 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.24.2" + "version": "3.24.3" }, "snippets": [ { diff --git a/packages/google-cloud-asset/setup.py b/packages/google-cloud-asset/setup.py index f9e8782a8e92..bd5a0db4a25c 100644 --- a/packages/google-cloud-asset/setup.py +++ b/packages/google-cloud-asset/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "google-cloud-org-policy >= 0.1.2, <2.0.0dev", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", diff --git a/packages/google-cloud-assured-workloads/CHANGELOG.md b/packages/google-cloud-assured-workloads/CHANGELOG.md index bca80e35b826..8adb77a22e35 100644 --- a/packages/google-cloud-assured-workloads/CHANGELOG.md +++ b/packages/google-cloud-assured-workloads/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.12.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-assured-workloads-v1.12.2...google-cloud-assured-workloads-v1.12.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [1.12.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-assured-workloads-v1.12.1...google-cloud-assured-workloads-v1.12.2) (2024-02-22) 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 394a70bae1a3..12049b60eb6c 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.12.2" # {x-release-please-version} +__version__ = "1.12.3" # {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 394a70bae1a3..12049b60eb6c 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.12.2" # {x-release-please-version} +__version__ = "1.12.3" # {x-release-please-version} 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 394a70bae1a3..12049b60eb6c 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.12.2" # {x-release-please-version} +__version__ = "1.12.3" # {x-release-please-version} 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 f4220fdaec02..4224200bbaed 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.12.2" + "version": "1.12.3" }, "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 d1f6cd91663d..051e3a29fc9f 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.12.2" + "version": "1.12.3" }, "snippets": [ { diff --git a/packages/google-cloud-assured-workloads/setup.py b/packages/google-cloud-assured-workloads/setup.py index b16d743a2d16..1f10c607b637 100644 --- a/packages/google-cloud-assured-workloads/setup.py +++ b/packages/google-cloud-assured-workloads/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-automl/CHANGELOG.md b/packages/google-cloud-automl/CHANGELOG.md index cc9395c3173f..3cc171ba911c 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.13.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-automl-v2.13.2...google-cloud-automl-v2.13.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12381](https://github.com/googleapis/google-cloud-python/issues/12381)) ([48ae8ab](https://github.com/googleapis/google-cloud-python/commit/48ae8aba7ec71a382e001b3a659022f942c3b436)) + ## [2.13.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-automl-v2.13.1...google-cloud-automl-v2.13.2) (2024-02-22) 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 d767d5ad8591..6c235a092e73 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.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {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 d767d5ad8591..6c235a092e73 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.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} 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 d767d5ad8591..6c235a092e73 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.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} 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 575f0615f027..7c9d8f526be8 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.13.2" + "version": "2.13.3" }, "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 4b274aa7033b..fff4857bb336 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.13.2" + "version": "2.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-automl/setup.py b/packages/google-cloud-automl/setup.py index 823bc756f461..1e8853092cde 100644 --- a/packages/google-cloud-automl/setup.py +++ b/packages/google-cloud-automl/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-bare-metal-solution/CHANGELOG.md b/packages/google-cloud-bare-metal-solution/CHANGELOG.md index c255d44e26cb..4078de60e4f4 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.7.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bare-metal-solution-v1.7.2...google-cloud-bare-metal-solution-v1.7.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [1.7.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bare-metal-solution-v1.7.1...google-cloud-bare-metal-solution-v1.7.2) (2024-02-22) 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 a71edaad33ab..84f198c2d605 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.7.2" # {x-release-please-version} +__version__ = "1.7.3" # {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 a71edaad33ab..84f198c2d605 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.7.2" # {x-release-please-version} +__version__ = "1.7.3" # {x-release-please-version} 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 fc65c9053dea..e5cc38c46fed 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.7.2" + "version": "1.7.3" }, "snippets": [ { diff --git a/packages/google-cloud-bare-metal-solution/setup.py b/packages/google-cloud-bare-metal-solution/setup.py index 7ac8f58c405a..8afa69556443 100644 --- a/packages/google-cloud-bare-metal-solution/setup.py +++ b/packages/google-cloud-bare-metal-solution/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-batch/CHANGELOG.md b/packages/google-cloud-batch/CHANGELOG.md index eb3d565738bd..5989fafa0be6 100644 --- a/packages/google-cloud-batch/CHANGELOG.md +++ b/packages/google-cloud-batch/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## [0.17.14](https://github.com/googleapis/google-cloud-python/compare/google-cloud-batch-v0.17.13...google-cloud-batch-v0.17.14) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + +## [0.17.13](https://github.com/googleapis/google-cloud-python/compare/google-cloud-batch-v0.17.12...google-cloud-batch-v0.17.13) (2024-03-04) + + +### Documentation + +* [google-cloud-batch] Remove UUID specification in comment ([#12366](https://github.com/googleapis/google-cloud-python/issues/12366)) ([13c7f8f](https://github.com/googleapis/google-cloud-python/commit/13c7f8f24450f520e4021336753c5a9219d52cf6)) +* [google-cloud-batch] update description of Job uid field ([13c7f8f](https://github.com/googleapis/google-cloud-python/commit/13c7f8f24450f520e4021336753c5a9219d52cf6)) + ## [0.17.12](https://github.com/googleapis/google-cloud-python/compare/google-cloud-batch-v0.17.11...google-cloud-batch-v0.17.12) (2024-02-22) 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 7f67df2cb9c1..8bfaa7a23671 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.12" # {x-release-please-version} +__version__ = "0.17.14" # {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 7f67df2cb9c1..8bfaa7a23671 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.12" # {x-release-please-version} +__version__ = "0.17.14" # {x-release-please-version} diff --git a/packages/google-cloud-batch/google/cloud/batch_v1/types/job.py b/packages/google-cloud-batch/google/cloud/batch_v1/types/job.py index 92d35f6d23b0..dbf3dc34903e 100644 --- a/packages/google-cloud-batch/google/cloud/batch_v1/types/job.py +++ b/packages/google-cloud-batch/google/cloud/batch_v1/types/job.py @@ -46,8 +46,8 @@ class Job(proto.Message): For example: "projects/123456/locations/us-central1/jobs/job01". uid (str): - Output only. A system generated unique ID (in - UUID4 format) for the Job. + Output only. A system generated unique ID for + the Job. priority (int): Priority of the Job. The valid value range is [0, 100). Default value is 0. Higher value indicates higher priority. 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 7f67df2cb9c1..8bfaa7a23671 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.12" # {x-release-please-version} +__version__ = "0.17.14" # {x-release-please-version} diff --git a/packages/google-cloud-batch/google/cloud/batch_v1alpha/types/job.py b/packages/google-cloud-batch/google/cloud/batch_v1alpha/types/job.py index e5281086e4b7..2d99b8e88adc 100644 --- a/packages/google-cloud-batch/google/cloud/batch_v1alpha/types/job.py +++ b/packages/google-cloud-batch/google/cloud/batch_v1alpha/types/job.py @@ -48,8 +48,8 @@ class Job(proto.Message): For example: "projects/123456/locations/us-central1/jobs/job01". uid (str): - Output only. A system generated unique ID (in - UUID4 format) for the Job. + Output only. A system generated unique ID for + the Job. priority (int): Priority of the Job. The valid value range is [0, 100). Default value is 0. Higher value indicates higher priority. 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 0c9222258cd9..53d5dece91e2 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.12" + "version": "0.17.14" }, "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 4d667a570409..a1b6ab4dbdf3 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.12" + "version": "0.17.14" }, "snippets": [ { diff --git a/packages/google-cloud-batch/setup.py b/packages/google-cloud-batch/setup.py index 3c209a7e3495..72bc6777bc71 100644 --- a/packages/google-cloud-batch/setup.py +++ b/packages/google-cloud-batch/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-beyondcorp-appconnections/CHANGELOG.md b/packages/google-cloud-beyondcorp-appconnections/CHANGELOG.md index 47dc20e84974..217f136b6e4e 100644 --- a/packages/google-cloud-beyondcorp-appconnections/CHANGELOG.md +++ b/packages/google-cloud-beyondcorp-appconnections/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.4.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-appconnections-v0.4.8...google-cloud-beyondcorp-appconnections-v0.4.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [0.4.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-appconnections-v0.4.7...google-cloud-beyondcorp-appconnections-v0.4.8) (2024-02-22) 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 38fe6bb9f3cb..08079bd6b988 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.8" # {x-release-please-version} +__version__ = "0.4.9" # {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 38fe6bb9f3cb..08079bd6b988 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.8" # {x-release-please-version} +__version__ = "0.4.9" # {x-release-please-version} 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 8ffa663284b9..2e1a4101e8e7 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.8" + "version": "0.4.9" }, "snippets": [ { diff --git a/packages/google-cloud-beyondcorp-appconnections/setup.py b/packages/google-cloud-beyondcorp-appconnections/setup.py index 1ac7e284ca7a..40b599a12b0c 100644 --- a/packages/google-cloud-beyondcorp-appconnections/setup.py +++ b/packages/google-cloud-beyondcorp-appconnections/setup.py @@ -44,7 +44,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-beyondcorp-appconnectors/CHANGELOG.md b/packages/google-cloud-beyondcorp-appconnectors/CHANGELOG.md index 250c5e33be62..d87ef843133a 100644 --- a/packages/google-cloud-beyondcorp-appconnectors/CHANGELOG.md +++ b/packages/google-cloud-beyondcorp-appconnectors/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.4.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-appconnectors-v0.4.8...google-cloud-beyondcorp-appconnectors-v0.4.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [0.4.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-appconnectors-v0.4.7...google-cloud-beyondcorp-appconnectors-v0.4.8) (2024-02-22) 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 38fe6bb9f3cb..08079bd6b988 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.8" # {x-release-please-version} +__version__ = "0.4.9" # {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 38fe6bb9f3cb..08079bd6b988 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.8" # {x-release-please-version} +__version__ = "0.4.9" # {x-release-please-version} 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 e4711c06a22e..5407864c6a8c 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.8" + "version": "0.4.9" }, "snippets": [ { diff --git a/packages/google-cloud-beyondcorp-appconnectors/setup.py b/packages/google-cloud-beyondcorp-appconnectors/setup.py index 9393903ca52c..8c642d9d07f9 100644 --- a/packages/google-cloud-beyondcorp-appconnectors/setup.py +++ b/packages/google-cloud-beyondcorp-appconnectors/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-beyondcorp-appgateways/CHANGELOG.md b/packages/google-cloud-beyondcorp-appgateways/CHANGELOG.md index 2846ee2051df..6c91a36d01e3 100644 --- a/packages/google-cloud-beyondcorp-appgateways/CHANGELOG.md +++ b/packages/google-cloud-beyondcorp-appgateways/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.4.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-appgateways-v0.4.8...google-cloud-beyondcorp-appgateways-v0.4.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [0.4.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-appgateways-v0.4.7...google-cloud-beyondcorp-appgateways-v0.4.8) (2024-02-22) 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 38fe6bb9f3cb..08079bd6b988 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.8" # {x-release-please-version} +__version__ = "0.4.9" # {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 38fe6bb9f3cb..08079bd6b988 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.8" # {x-release-please-version} +__version__ = "0.4.9" # {x-release-please-version} 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 640fa00cc5b0..c7a2ea4465fe 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.8" + "version": "0.4.9" }, "snippets": [ { diff --git a/packages/google-cloud-beyondcorp-appgateways/setup.py b/packages/google-cloud-beyondcorp-appgateways/setup.py index 3755918ea697..394a2b67060d 100644 --- a/packages/google-cloud-beyondcorp-appgateways/setup.py +++ b/packages/google-cloud-beyondcorp-appgateways/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-beyondcorp-clientconnectorservices/CHANGELOG.md b/packages/google-cloud-beyondcorp-clientconnectorservices/CHANGELOG.md index 51f5ed3d24b8..f3443a8d22d7 100644 --- a/packages/google-cloud-beyondcorp-clientconnectorservices/CHANGELOG.md +++ b/packages/google-cloud-beyondcorp-clientconnectorservices/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.4.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-clientconnectorservices-v0.4.8...google-cloud-beyondcorp-clientconnectorservices-v0.4.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [0.4.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-clientconnectorservices-v0.4.7...google-cloud-beyondcorp-clientconnectorservices-v0.4.8) (2024-02-22) 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 38fe6bb9f3cb..08079bd6b988 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.8" # {x-release-please-version} +__version__ = "0.4.9" # {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 38fe6bb9f3cb..08079bd6b988 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.8" # {x-release-please-version} +__version__ = "0.4.9" # {x-release-please-version} 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 30608468fd06..88419b740473 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.8" + "version": "0.4.9" }, "snippets": [ { diff --git a/packages/google-cloud-beyondcorp-clientconnectorservices/setup.py b/packages/google-cloud-beyondcorp-clientconnectorservices/setup.py index 4f82a750d80d..75545f039e2b 100644 --- a/packages/google-cloud-beyondcorp-clientconnectorservices/setup.py +++ b/packages/google-cloud-beyondcorp-clientconnectorservices/setup.py @@ -44,7 +44,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-beyondcorp-clientgateways/CHANGELOG.md b/packages/google-cloud-beyondcorp-clientgateways/CHANGELOG.md index 9b9c48905658..1969ea3e9663 100644 --- a/packages/google-cloud-beyondcorp-clientgateways/CHANGELOG.md +++ b/packages/google-cloud-beyondcorp-clientgateways/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.4.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-clientgateways-v0.4.7...google-cloud-beyondcorp-clientgateways-v0.4.8) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [0.4.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-beyondcorp-clientgateways-v0.4.6...google-cloud-beyondcorp-clientgateways-v0.4.7) (2024-02-22) 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 05392921a87c..38fe6bb9f3cb 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.7" # {x-release-please-version} +__version__ = "0.4.8" # {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 05392921a87c..38fe6bb9f3cb 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.7" # {x-release-please-version} +__version__ = "0.4.8" # {x-release-please-version} 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 18d613ae7659..385e3dc90e54 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.7" + "version": "0.4.8" }, "snippets": [ { diff --git a/packages/google-cloud-beyondcorp-clientgateways/setup.py b/packages/google-cloud-beyondcorp-clientgateways/setup.py index e16af1f44e54..e56812f238f5 100644 --- a/packages/google-cloud-beyondcorp-clientgateways/setup.py +++ b/packages/google-cloud-beyondcorp-clientgateways/setup.py @@ -44,7 +44,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-bigquery-analyticshub/CHANGELOG.md b/packages/google-cloud-bigquery-analyticshub/CHANGELOG.md index 6144dc4d9aa5..289e5ec109bb 100644 --- a/packages/google-cloud-bigquery-analyticshub/CHANGELOG.md +++ b/packages/google-cloud-bigquery-analyticshub/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.4.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-analyticshub-v0.4.7...google-cloud-bigquery-analyticshub-v0.4.8) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [0.4.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-analyticshub-v0.4.6...google-cloud-bigquery-analyticshub-v0.4.7) (2024-02-22) 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 05392921a87c..38fe6bb9f3cb 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.7" # {x-release-please-version} +__version__ = "0.4.8" # {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 05392921a87c..38fe6bb9f3cb 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.7" # {x-release-please-version} +__version__ = "0.4.8" # {x-release-please-version} 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 908aff809360..4b0ef8191430 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.7" + "version": "0.4.8" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-analyticshub/setup.py b/packages/google-cloud-bigquery-analyticshub/setup.py index 79f0b1c1f0e2..2b96cb800ae5 100644 --- a/packages/google-cloud-bigquery-analyticshub/setup.py +++ b/packages/google-cloud-bigquery-analyticshub/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-bigquery-biglake/CHANGELOG.md b/packages/google-cloud-bigquery-biglake/CHANGELOG.md index 52633a485a08..5e6d149ca18b 100644 --- a/packages/google-cloud-bigquery-biglake/CHANGELOG.md +++ b/packages/google-cloud-bigquery-biglake/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.4.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-biglake-v0.4.6...google-cloud-bigquery-biglake-v0.4.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [0.4.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-biglake-v0.4.5...google-cloud-bigquery-biglake-v0.4.6) (2024-02-22) 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 7c932adae91d..05392921a87c 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.6" # {x-release-please-version} +__version__ = "0.4.7" # {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 7c932adae91d..05392921a87c 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.6" # {x-release-please-version} +__version__ = "0.4.7" # {x-release-please-version} 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 7c932adae91d..05392921a87c 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.6" # {x-release-please-version} +__version__ = "0.4.7" # {x-release-please-version} 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 92043a60ddcb..4ac01730c4fe 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.6" + "version": "0.4.7" }, "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 7ff0fc813236..53636cb84f5e 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.6" + "version": "0.4.7" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-biglake/setup.py b/packages/google-cloud-bigquery-biglake/setup.py index 0eec09ffe450..3e4b89cf5426 100644 --- a/packages/google-cloud-bigquery-biglake/setup.py +++ b/packages/google-cloud-bigquery-biglake/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-bigquery-connection/CHANGELOG.md b/packages/google-cloud-bigquery-connection/CHANGELOG.md index aadf645a9bf3..fe2e222fdce2 100644 --- a/packages/google-cloud-bigquery-connection/CHANGELOG.md +++ b/packages/google-cloud-bigquery-connection/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.15.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-connection-v1.15.2...google-cloud-bigquery-connection-v1.15.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [1.15.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-connection-v1.15.1...google-cloud-bigquery-connection-v1.15.2) (2024-02-22) 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 2b083704400c..7f190df1d2bb 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.15.2" # {x-release-please-version} +__version__ = "1.15.3" # {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 2b083704400c..7f190df1d2bb 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.15.2" # {x-release-please-version} +__version__ = "1.15.3" # {x-release-please-version} 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 46ede86a809f..58a04407697f 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.15.2" + "version": "1.15.3" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-connection/setup.py b/packages/google-cloud-bigquery-connection/setup.py index 0e3b015ccb33..f8fdf0b9dbfc 100644 --- a/packages/google-cloud-bigquery-connection/setup.py +++ b/packages/google-cloud-bigquery-connection/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-bigquery-data-exchange/CHANGELOG.md b/packages/google-cloud-bigquery-data-exchange/CHANGELOG.md index dc74d7c75b1f..feb56541c233 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.11](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-data-exchange-v0.5.10...google-cloud-bigquery-data-exchange-v0.5.11) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [0.5.10](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-data-exchange-v0.5.9...google-cloud-bigquery-data-exchange-v0.5.10) (2024-02-22) 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 9afb8fa5aadb..9488fffe3b96 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.10" # {x-release-please-version} +__version__ = "0.5.11" # {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 9afb8fa5aadb..9488fffe3b96 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.10" # {x-release-please-version} +__version__ = "0.5.11" # {x-release-please-version} 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 25713f6828a1..26adb4736885 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.10" + "version": "0.5.11" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-data-exchange/setup.py b/packages/google-cloud-bigquery-data-exchange/setup.py index 534e82dd563c..877ff6133c13 100644 --- a/packages/google-cloud-bigquery-data-exchange/setup.py +++ b/packages/google-cloud-bigquery-data-exchange/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-bigquery-datapolicies/CHANGELOG.md b/packages/google-cloud-bigquery-datapolicies/CHANGELOG.md index 713a819bb5bf..2e430ed4231c 100644 --- a/packages/google-cloud-bigquery-datapolicies/CHANGELOG.md +++ b/packages/google-cloud-bigquery-datapolicies/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.6.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-datapolicies-v0.6.5...google-cloud-bigquery-datapolicies-v0.6.6) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [0.6.5](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-datapolicies-v0.6.4...google-cloud-bigquery-datapolicies-v0.6.5) (2024-02-22) 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 7257802240c5..31104fb7ab8e 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.5" # {x-release-please-version} +__version__ = "0.6.6" # {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 7257802240c5..31104fb7ab8e 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.5" # {x-release-please-version} +__version__ = "0.6.6" # {x-release-please-version} 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 7257802240c5..31104fb7ab8e 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.5" # {x-release-please-version} +__version__ = "0.6.6" # {x-release-please-version} 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 09e6ed0ae33a..53f3d4f36717 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.5" + "version": "0.6.6" }, "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 72373587389f..2a4a82b4d30d 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.5" + "version": "0.6.6" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-datapolicies/setup.py b/packages/google-cloud-bigquery-datapolicies/setup.py index 0012020935f6..08bbe7897440 100644 --- a/packages/google-cloud-bigquery-datapolicies/setup.py +++ b/packages/google-cloud-bigquery-datapolicies/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-bigquery-datatransfer/CHANGELOG.md b/packages/google-cloud-bigquery-datatransfer/CHANGELOG.md index b5f8d9fd85c7..eca21b4cdbee 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.15.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-datatransfer-v3.15.0...google-cloud-bigquery-datatransfer-v3.15.1) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [3.15.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-datatransfer-v3.14.1...google-cloud-bigquery-datatransfer-v3.15.0) (2024-02-22) 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 440d5b96bed5..27cd8e965aa3 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.15.0" # {x-release-please-version} +__version__ = "3.15.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 440d5b96bed5..27cd8e965aa3 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.15.0" # {x-release-please-version} +__version__ = "3.15.1" # {x-release-please-version} 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 152a26906d9c..5ed2f70e1cdc 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.15.0" + "version": "3.15.1" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-datatransfer/setup.py b/packages/google-cloud-bigquery-datatransfer/setup.py index ad3cabae059b..53c7b6c187a0 100644 --- a/packages/google-cloud-bigquery-datatransfer/setup.py +++ b/packages/google-cloud-bigquery-datatransfer/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-bigquery-logging/CHANGELOG.md b/packages/google-cloud-bigquery-logging/CHANGELOG.md index 9cabad5af93f..7366633e700d 100644 --- a/packages/google-cloud-bigquery-logging/CHANGELOG.md +++ b/packages/google-cloud-bigquery-logging/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.4.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-logging-v1.4.2...google-cloud-bigquery-logging-v1.4.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [1.4.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-logging-v1.4.1...google-cloud-bigquery-logging-v1.4.2) (2024-02-22) diff --git a/packages/google-cloud-bigquery-logging/google/cloud/bigquery_logging/gapic_version.py b/packages/google-cloud-bigquery-logging/google/cloud/bigquery_logging/gapic_version.py index 51f58966561e..4f9b5347cdbf 100644 --- a/packages/google-cloud-bigquery-logging/google/cloud/bigquery_logging/gapic_version.py +++ b/packages/google-cloud-bigquery-logging/google/cloud/bigquery_logging/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.4.2" # {x-release-please-version} +__version__ = "1.4.3" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-logging/google/cloud/bigquery_logging_v1/gapic_version.py b/packages/google-cloud-bigquery-logging/google/cloud/bigquery_logging_v1/gapic_version.py index 51f58966561e..4f9b5347cdbf 100644 --- a/packages/google-cloud-bigquery-logging/google/cloud/bigquery_logging_v1/gapic_version.py +++ b/packages/google-cloud-bigquery-logging/google/cloud/bigquery_logging_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.4.2" # {x-release-please-version} +__version__ = "1.4.3" # {x-release-please-version} diff --git a/packages/google-cloud-bigquery-logging/setup.py b/packages/google-cloud-bigquery-logging/setup.py index 1c10fed837d3..348beb9494a1 100644 --- a/packages/google-cloud-bigquery-logging/setup.py +++ b/packages/google-cloud-bigquery-logging/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-bigquery-migration/CHANGELOG.md b/packages/google-cloud-bigquery-migration/CHANGELOG.md index 536ac906b887..d31bc407014c 100644 --- a/packages/google-cloud-bigquery-migration/CHANGELOG.md +++ b/packages/google-cloud-bigquery-migration/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.11.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-migration-v0.11.6...google-cloud-bigquery-migration-v0.11.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [0.11.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-migration-v0.11.5...google-cloud-bigquery-migration-v0.11.6) (2024-02-22) 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 76197bc2c0db..fb9a6cb2d900 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.6" # {x-release-please-version} +__version__ = "0.11.7" # {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 76197bc2c0db..fb9a6cb2d900 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.6" # {x-release-please-version} +__version__ = "0.11.7" # {x-release-please-version} 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 76197bc2c0db..fb9a6cb2d900 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.6" # {x-release-please-version} +__version__ = "0.11.7" # {x-release-please-version} 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 dd2d5aa12bd5..bb39e6a9ef67 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.6" + "version": "0.11.7" }, "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 d888b51e5340..08dc34331586 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.6" + "version": "0.11.7" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-migration/setup.py b/packages/google-cloud-bigquery-migration/setup.py index 6028addf5342..7037a57dc104 100644 --- a/packages/google-cloud-bigquery-migration/setup.py +++ b/packages/google-cloud-bigquery-migration/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-bigquery-reservation/CHANGELOG.md b/packages/google-cloud-bigquery-reservation/CHANGELOG.md index fc302db3fb02..64bc9205014c 100644 --- a/packages/google-cloud-bigquery-reservation/CHANGELOG.md +++ b/packages/google-cloud-bigquery-reservation/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.13.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-reservation-v1.13.2...google-cloud-bigquery-reservation-v1.13.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [1.13.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-bigquery-reservation-v1.13.1...google-cloud-bigquery-reservation-v1.13.2) (2024-02-22) 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 3434b217efee..40e034931fac 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.13.2" # {x-release-please-version} +__version__ = "1.13.3" # {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 3434b217efee..40e034931fac 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.13.2" # {x-release-please-version} +__version__ = "1.13.3" # {x-release-please-version} 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 52a43dddefd1..fc54af798214 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.13.2" + "version": "1.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-bigquery-reservation/setup.py b/packages/google-cloud-bigquery-reservation/setup.py index 2a23f929cc6c..e8e801ab60f4 100644 --- a/packages/google-cloud-bigquery-reservation/setup.py +++ b/packages/google-cloud-bigquery-reservation/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-billing-budgets/CHANGELOG.md b/packages/google-cloud-billing-budgets/CHANGELOG.md index 01b27392590c..a389f275ae42 100644 --- a/packages/google-cloud-billing-budgets/CHANGELOG.md +++ b/packages/google-cloud-billing-budgets/CHANGELOG.md @@ -1,4 +1,11 @@ # Changelog +## [1.14.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-billing-budgets-v1.14.2...google-cloud-billing-budgets-v1.14.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [1.14.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-billing-budgets-v1.14.1...google-cloud-billing-budgets-v1.14.2) (2024-02-22) 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 5612fcf86156..616be6a7ff08 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.14.2" # {x-release-please-version} +__version__ = "1.14.3" # {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 5612fcf86156..616be6a7ff08 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.14.2" # {x-release-please-version} +__version__ = "1.14.3" # {x-release-please-version} 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 5612fcf86156..616be6a7ff08 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.14.2" # {x-release-please-version} +__version__ = "1.14.3" # {x-release-please-version} 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 72fab9a7308c..83c971d5fb72 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.14.2" + "version": "1.14.3" }, "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 97e79e5f6491..b38e91e796b7 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.14.2" + "version": "1.14.3" }, "snippets": [ { diff --git a/packages/google-cloud-billing-budgets/setup.py b/packages/google-cloud-billing-budgets/setup.py index d0d70f986ce4..017903ef56a2 100644 --- a/packages/google-cloud-billing-budgets/setup.py +++ b/packages/google-cloud-billing-budgets/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-billing/CHANGELOG.md b/packages/google-cloud-billing/CHANGELOG.md index 7c56b718c6c3..926b95c761e0 100644 --- a/packages/google-cloud-billing/CHANGELOG.md +++ b/packages/google-cloud-billing/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.13.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-billing-v1.13.2...google-cloud-billing-v1.13.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [1.13.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-billing-v1.13.1...google-cloud-billing-v1.13.2) (2024-02-22) 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 3434b217efee..40e034931fac 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.13.2" # {x-release-please-version} +__version__ = "1.13.3" # {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 3434b217efee..40e034931fac 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.13.2" # {x-release-please-version} +__version__ = "1.13.3" # {x-release-please-version} 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 a5a601dcf9da..4ffe509083ae 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.13.2" + "version": "1.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-billing/setup.py b/packages/google-cloud-billing/setup.py index 0517430e6164..2d635b1f1948 100644 --- a/packages/google-cloud-billing/setup.py +++ b/packages/google-cloud-billing/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-binary-authorization/CHANGELOG.md b/packages/google-cloud-binary-authorization/CHANGELOG.md index 0d0aaaedc5ff..204d21498650 100644 --- a/packages/google-cloud-binary-authorization/CHANGELOG.md +++ b/packages/google-cloud-binary-authorization/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.10.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-binary-authorization-v1.10.2...google-cloud-binary-authorization-v1.10.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [1.10.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-binary-authorization-v1.10.1...google-cloud-binary-authorization-v1.10.2) (2024-02-22) 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 7a033a50e6cd..d74c07c1961e 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.10.2" # {x-release-please-version} +__version__ = "1.10.3" # {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 7a033a50e6cd..d74c07c1961e 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.10.2" # {x-release-please-version} +__version__ = "1.10.3" # {x-release-please-version} 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 7a033a50e6cd..d74c07c1961e 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.10.2" # {x-release-please-version} +__version__ = "1.10.3" # {x-release-please-version} 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 14a48c0394d8..b1d4d6178d02 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.10.2" + "version": "1.10.3" }, "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 55a89b164372..a7eec9e2b24a 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.10.2" + "version": "1.10.3" }, "snippets": [ { diff --git a/packages/google-cloud-binary-authorization/setup.py b/packages/google-cloud-binary-authorization/setup.py index 511e7d9fd165..e07588779209 100644 --- a/packages/google-cloud-binary-authorization/setup.py +++ b/packages/google-cloud-binary-authorization/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "grafeas >= 1.1.2, <2.0dev", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", diff --git a/packages/google-cloud-build/CHANGELOG.md b/packages/google-cloud-build/CHANGELOG.md index 2ed61f32abd0..d91f76c74731 100644 --- a/packages/google-cloud-build/CHANGELOG.md +++ b/packages/google-cloud-build/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-build/#history +## [3.23.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-build-v3.23.2...google-cloud-build-v3.23.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12382](https://github.com/googleapis/google-cloud-python/issues/12382)) ([d5db265](https://github.com/googleapis/google-cloud-python/commit/d5db2656c011be2264bd778244caf8e23d288c75)) + ## [3.23.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-build-v3.23.1...google-cloud-build-v3.23.2) (2024-02-22) diff --git a/packages/google-cloud-build/google/cloud/devtools/cloudbuild/gapic_version.py b/packages/google-cloud-build/google/cloud/devtools/cloudbuild/gapic_version.py index f451535d7360..72b084e21a4b 100644 --- a/packages/google-cloud-build/google/cloud/devtools/cloudbuild/gapic_version.py +++ b/packages/google-cloud-build/google/cloud/devtools/cloudbuild/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.23.2" # {x-release-please-version} +__version__ = "3.23.3" # {x-release-please-version} diff --git a/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v1/gapic_version.py b/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v1/gapic_version.py index f451535d7360..72b084e21a4b 100644 --- a/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v1/gapic_version.py +++ b/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.23.2" # {x-release-please-version} +__version__ = "3.23.3" # {x-release-please-version} diff --git a/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v2/gapic_version.py b/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v2/gapic_version.py index f451535d7360..72b084e21a4b 100644 --- a/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v2/gapic_version.py +++ b/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.23.2" # {x-release-please-version} +__version__ = "3.23.3" # {x-release-please-version} diff --git a/packages/google-cloud-build/samples/generated_samples/snippet_metadata_google.devtools.cloudbuild.v1.json b/packages/google-cloud-build/samples/generated_samples/snippet_metadata_google.devtools.cloudbuild.v1.json index 1abb7a0efc78..892e811efb1c 100644 --- a/packages/google-cloud-build/samples/generated_samples/snippet_metadata_google.devtools.cloudbuild.v1.json +++ b/packages/google-cloud-build/samples/generated_samples/snippet_metadata_google.devtools.cloudbuild.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-build", - "version": "3.23.2" + "version": "3.23.3" }, "snippets": [ { diff --git a/packages/google-cloud-build/samples/generated_samples/snippet_metadata_google.devtools.cloudbuild.v2.json b/packages/google-cloud-build/samples/generated_samples/snippet_metadata_google.devtools.cloudbuild.v2.json index 71fc4d77038e..555bb49bca03 100644 --- a/packages/google-cloud-build/samples/generated_samples/snippet_metadata_google.devtools.cloudbuild.v2.json +++ b/packages/google-cloud-build/samples/generated_samples/snippet_metadata_google.devtools.cloudbuild.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-build", - "version": "3.23.2" + "version": "3.23.3" }, "snippets": [ { diff --git a/packages/google-cloud-build/setup.py b/packages/google-cloud-build/setup.py index ae1d714a4030..9bbfe3ef2897 100644 --- a/packages/google-cloud-build/setup.py +++ b/packages/google-cloud-build/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "grpc-google-iam-v1 >=0.12.4, <1.0.0dev", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", diff --git a/packages/google-cloud-certificate-manager/CHANGELOG.md b/packages/google-cloud-certificate-manager/CHANGELOG.md index e547c726418f..79bacf30f3bb 100644 --- a/packages/google-cloud-certificate-manager/CHANGELOG.md +++ b/packages/google-cloud-certificate-manager/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.6.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-certificate-manager-v1.6.2...google-cloud-certificate-manager-v1.6.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [1.6.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-certificate-manager-v1.6.1...google-cloud-certificate-manager-v1.6.2) (2024-02-22) 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 5a04fdf276c9..fc429472f4c9 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.6.2" # {x-release-please-version} +__version__ = "1.6.3" # {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 5a04fdf276c9..fc429472f4c9 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.6.2" # {x-release-please-version} +__version__ = "1.6.3" # {x-release-please-version} 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 e3e7a2dfcb15..20aa81585c14 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.6.2" + "version": "1.6.3" }, "snippets": [ { diff --git a/packages/google-cloud-certificate-manager/setup.py b/packages/google-cloud-certificate-manager/setup.py index ec3bf4ac0f3d..85997b0981f3 100644 --- a/packages/google-cloud-certificate-manager/setup.py +++ b/packages/google-cloud-certificate-manager/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-channel/CHANGELOG.md b/packages/google-cloud-channel/CHANGELOG.md index e1d671d1a2aa..e8f15b4b5ced 100644 --- a/packages/google-cloud-channel/CHANGELOG.md +++ b/packages/google-cloud-channel/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.18.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-channel-v1.18.2...google-cloud-channel-v1.18.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [1.18.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-channel-v1.18.1...google-cloud-channel-v1.18.2) (2024-02-22) 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 00ba0d9a60cd..07b9890caafb 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.18.2" # {x-release-please-version} +__version__ = "1.18.3" # {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 00ba0d9a60cd..07b9890caafb 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.18.2" # {x-release-please-version} +__version__ = "1.18.3" # {x-release-please-version} 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 be5054f59bc2..8f10a077ef5f 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.18.2" + "version": "1.18.3" }, "snippets": [ { diff --git a/packages/google-cloud-channel/setup.py b/packages/google-cloud-channel/setup.py index 8412b2779e9f..e74191436b4d 100644 --- a/packages/google-cloud-channel/setup.py +++ b/packages/google-cloud-channel/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-cloudcontrolspartner/.OwlBot.yaml b/packages/google-cloud-cloudcontrolspartner/.OwlBot.yaml new file mode 100644 index 000000000000..ab372e8f04ea --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/.OwlBot.yaml @@ -0,0 +1,18 @@ +# Copyright 2022 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. + +deep-copy-regex: + - source: /google/cloud/cloudcontrolspartner/(v.*)/.*-py + dest: /owl-bot-staging/google-cloud-cloudcontrolspartner/$1 +api-name: google-cloud-cloudcontrolspartner diff --git a/packages/google-cloud-cloudcontrolspartner/.coveragerc b/packages/google-cloud-cloudcontrolspartner/.coveragerc new file mode 100644 index 000000000000..a2e177ef5464 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/cloudcontrolspartner/__init__.py + google/cloud/cloudcontrolspartner/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/packages/google-cloud-cloudcontrolspartner/.flake8 b/packages/google-cloud-cloudcontrolspartner/.flake8 new file mode 100644 index 000000000000..87f6e408c47d --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2023 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 +# +# https://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 by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E231, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/packages/google-cloud-cloudcontrolspartner/.gitignore b/packages/google-cloud-cloudcontrolspartner/.gitignore new file mode 100644 index 000000000000..b4243ced74e4 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/.gitignore @@ -0,0 +1,63 @@ +*.py[cod] +*.sw[op] + +# C extensions +*.so + +# Packages +*.egg +*.egg-info +dist +build +eggs +.eggs +parts +bin +var +sdist +develop-eggs +.installed.cfg +lib +lib64 +__pycache__ + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.nox +.cache +.pytest_cache + + +# Mac +.DS_Store + +# JetBrains +.idea + +# VS Code +.vscode + +# emacs +*~ + +# Built documentation +docs/_build +bigquery/docs/generated +docs.metadata + +# Virtual environment +env/ + +# Test logs +coverage.xml +*sponge_log.xml + +# System test environment variables. +system_tests/local_test_setup + +# Make sure a generated file isn't accidentally committed. +pylintrc +pylintrc.test diff --git a/packages/google-cloud-cloudcontrolspartner/.repo-metadata.json b/packages/google-cloud-cloudcontrolspartner/.repo-metadata.json new file mode 100644 index 000000000000..c830f51bf3d0 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/.repo-metadata.json @@ -0,0 +1,17 @@ +{ + "name": "google-cloud-cloudcontrolspartner", + "name_pretty": "Cloud Controls Partner API", + "api_description": "Provides insights about your customers and their Assured Workloads based on your Sovereign Controls by Partners offering.", + "product_documentation": "https://cloud.google.com/sovereign-controls-by-partners/docs/sovereign-partners/reference/rest", + "client_documentation": "https://cloud.google.com/python/docs/reference/google-cloud-cloudcontrolspartner/latest", + "issue_tracker": "https://github.com/googleapis/google-cloud-python/issues", + "release_level": "preview", + "language": "python", + "library_type": "GAPIC_AUTO", + "repo": "googleapis/google-cloud-python", + "distribution_name": "google-cloud-cloudcontrolspartner", + "api_id": "cloudcontrolspartner.googleapis.com", + "default_version": "v1", + "codeowner_team": "", + "api_shortname": "cloudcontrolspartner" +} diff --git a/packages/google-cloud-cloudcontrolspartner/CHANGELOG.md b/packages/google-cloud-cloudcontrolspartner/CHANGELOG.md new file mode 100644 index 000000000000..2229c9e09772 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +## 0.1.0 (2024-03-05) + + +### Features + +* add initial files for google.cloud.cloudcontrolspartner.v1 ([#12402](https://github.com/googleapis/google-cloud-python/issues/12402)) ([7cd0f05](https://github.com/googleapis/google-cloud-python/commit/7cd0f0541ededa589eb76a6d8a965849834734c9)) + +## Changelog diff --git a/packages/google-cloud-cloudcontrolspartner/CODE_OF_CONDUCT.md b/packages/google-cloud-cloudcontrolspartner/CODE_OF_CONDUCT.md new file mode 100644 index 000000000000..039f43681204 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/CODE_OF_CONDUCT.md @@ -0,0 +1,95 @@ + +# Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of +experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, or to ban temporarily or permanently any +contributor for other behaviors that they deem inappropriate, threatening, +offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +This Code of Conduct also applies outside the project spaces when the Project +Steward has a reasonable belief that an individual's behavior may have a +negative impact on the project or its community. + +## Conflict Resolution + +We do not believe that all conflict is bad; healthy debate and disagreement +often yield positive results. However, it is never okay to be disrespectful or +to engage in behavior that violates the project’s code of conduct. + +If you see someone violating the code of conduct, you are encouraged to address +the behavior directly with those involved. Many issues can be resolved quickly +and easily, and this gives people more control over the outcome of their +dispute. If you are unable to resolve the matter for any reason, or if the +behavior is threatening or harassing, report it. We are dedicated to providing +an environment where participants feel welcome and safe. + + +Reports should be directed to *googleapis-stewards@google.com*, the +Project Steward(s) for *Google Cloud Client Libraries*. It is the Project Steward’s duty to +receive and address reported violations of the code of conduct. They will then +work with a committee consisting of representatives from the Open Source +Programs Office and the Google Open Source Strategy team. If for any reason you +are uncomfortable reaching out to the Project Steward, please email +opensource@google.com. + +We will investigate every complaint, but you may not receive a direct response. +We will use our discretion in determining when and how to follow up on reported +incidents, which may range from not taking action to permanent expulsion from +the project and project-sponsored spaces. We will notify the accused of the +report and provide them an opportunity to discuss it before any action is taken. +The identity of the reporter will be omitted from the details of the report +supplied to the accused. In potentially harmful situations, such as ongoing +harassment or threats to anyone's safety, we may take action without notice. + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 1.4, +available at +https://www.contributor-covenant.org/version/1/4/code-of-conduct.html \ No newline at end of file diff --git a/packages/google-cloud-cloudcontrolspartner/CONTRIBUTING.rst b/packages/google-cloud-cloudcontrolspartner/CONTRIBUTING.rst new file mode 100644 index 000000000000..3550e8851a74 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/CONTRIBUTING.rst @@ -0,0 +1,271 @@ +.. Generated by synthtool. DO NOT EDIT! +############ +Contributing +############ + +#. **Please sign one of the contributor license agreements below.** +#. Fork the repo, develop and test your code changes, add docs. +#. Make sure that your commit messages clearly describe the changes. +#. Send a pull request. (Please Read: `Faster Pull Request Reviews`_) + +.. _Faster Pull Request Reviews: https://github.com/kubernetes/community/blob/master/contributors/guide/pull-requests.md#best-practices-for-faster-reviews + +.. contents:: Here are some guidelines for hacking on the Google Cloud Client libraries. + +*************** +Adding Features +*************** + +In order to add a feature: + +- The feature must be documented in both the API and narrative + documentation. + +- The feature must work fully on the following CPython versions: + 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + +- The feature must not add unnecessary dependencies (where + "unnecessary" is of course subjective, but new dependencies should + be discussed). + +**************************** +Using a Development Checkout +**************************** + +You'll have to create a development environment using a Git checkout: + +- While logged into your GitHub account, navigate to the + ``google-cloud-python`` `repo`_ on GitHub. + +- Fork and clone the ``google-cloud-python`` repository to your GitHub account by + clicking the "Fork" button. + +- Clone your fork of ``google-cloud-python`` from your GitHub account to your local + computer, substituting your account username and specifying the destination + as ``hack-on-google-cloud-python``. E.g.:: + + $ cd ${HOME} + $ git clone git@github.com:USERNAME/google-cloud-python.git hack-on-google-cloud-python + $ cd hack-on-google-cloud-python + # Configure remotes such that you can pull changes from the googleapis/google-cloud-python + # repository into your local repository. + $ git remote add upstream git@github.com:googleapis/google-cloud-python.git + # fetch and merge changes from upstream into main + $ git fetch upstream + $ git merge upstream/main + +Now your local repo is set up such that you will push changes to your GitHub +repo, from which you can submit a pull request. + +To work on the codebase and run the tests, we recommend using ``nox``, +but you can also use a ``virtualenv`` of your own creation. + +.. _repo: https://github.com/googleapis/google-cloud-python + +Using ``nox`` +============= + +We use `nox `__ to instrument our tests. + +- To test your changes, run unit tests with ``nox``:: + $ nox -s unit + +- To run a single unit test:: + + $ nox -s unit-3.12 -- -k + + + .. note:: + + The unit tests and system tests are described in the + ``noxfile.py`` files in each directory. + +.. nox: https://pypi.org/project/nox/ + +***************************************** +I'm getting weird errors... Can you help? +***************************************** + +If the error mentions ``Python.h`` not being found, +install ``python-dev`` and try again. +On Debian/Ubuntu:: + + $ sudo apt-get install python-dev + +************ +Coding Style +************ +- We use the automatic code formatter ``black``. You can run it using + the nox session ``blacken``. This will eliminate many lint errors. Run via:: + + $ nox -s blacken + +- PEP8 compliance is required, with exceptions defined in the linter configuration. + If you have ``nox`` installed, you can test that you have not introduced + any non-compliant code via:: + + $ nox -s lint + +- In order to make ``nox -s lint`` run faster, you can set some environment + variables:: + + export GOOGLE_CLOUD_TESTING_REMOTE="upstream" + export GOOGLE_CLOUD_TESTING_BRANCH="main" + + By doing this, you are specifying the location of the most up-to-date + version of ``google-cloud-python``. The + remote name ``upstream`` should point to the official ``googleapis`` + checkout and the branch should be the default branch on that remote (``main``). + +- This repository contains configuration for the + `pre-commit `__ tool, which automates checking + our linters during a commit. If you have it installed on your ``$PATH``, + you can enable enforcing those checks via: + +.. code-block:: bash + + $ pre-commit install + pre-commit installed at .git/hooks/pre-commit + +Exceptions to PEP8: + +- Many unit tests use a helper method, ``_call_fut`` ("FUT" is short for + "Function-Under-Test"), which is PEP8-incompliant, but more readable. + Some also use a local variable, ``MUT`` (short for "Module-Under-Test"). + +******************** +Running System Tests +******************** + +- To run system tests, you can execute:: + + # Run all system tests + $ nox -s system + + # Run a single system test + $ nox -s system-3.12 -- -k + + + .. note:: + + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + For expediency, we do not run them in older versions of Python 3. + + This alone will not run the tests. You'll need to change some local + auth settings and change some configuration in your project to + run all the tests. + +- System tests will be run against an actual project. You should use local credentials from gcloud when possible. See `Best practices for application authentication `__. Some tests require a service account. For those tests see `Authenticating as a service account `__. + +************* +Test Coverage +************* + +- The codebase *must* have 100% test statement coverage after each commit. + You can test coverage via ``nox -s cover``. + +****************************************************** +Documentation Coverage and Building HTML Documentation +****************************************************** + +If you fix a bug, and the bug requires an API or behavior modification, all +documentation in this package which references that API or behavior must be +changed to reflect the bug fix, ideally in the same commit that fixes the bug +or adds the feature. + +Build the docs via: + + $ nox -s docs + +************************* +Samples and code snippets +************************* + +Code samples and snippets live in the `samples/` catalogue. Feel free to +provide more examples, but make sure to write tests for those examples. +Each folder containing example code requires its own `noxfile.py` script +which automates testing. If you decide to create a new folder, you can +base it on the `samples/snippets` folder (providing `noxfile.py` and +the requirements files). + +The tests will run against a real Google Cloud Project, so you should +configure them just like the System Tests. + +- To run sample tests, you can execute:: + + # Run all tests in a folder + $ cd samples/snippets + $ nox -s py-3.8 + + # Run a single sample test + $ cd samples/snippets + $ nox -s py-3.8 -- -k + +******************************************** +Note About ``README`` as it pertains to PyPI +******************************************** + +The `description on PyPI`_ for the project comes directly from the +``README``. Due to the reStructuredText (``rst``) parser used by +PyPI, relative links which will work on GitHub (e.g. ``CONTRIBUTING.rst`` +instead of +``https://github.com/googleapis/google-cloud-python/blob/main/CONTRIBUTING.rst``) +may cause problems creating links or rendering the description. + +.. _description on PyPI: https://pypi.org/project/google-cloud-cloudcontrolspartner + + +************************* +Supported Python Versions +************************* + +We support: + +- `Python 3.7`_ +- `Python 3.8`_ +- `Python 3.9`_ +- `Python 3.10`_ +- `Python 3.11`_ +- `Python 3.12`_ + +.. _Python 3.7: https://docs.python.org/3.7/ +.. _Python 3.8: https://docs.python.org/3.8/ +.. _Python 3.9: https://docs.python.org/3.9/ +.. _Python 3.10: https://docs.python.org/3.10/ +.. _Python 3.11: https://docs.python.org/3.11/ +.. _Python 3.12: https://docs.python.org/3.12/ + + +Supported versions can be found in our ``noxfile.py`` `config`_. + +.. _config: https://github.com/googleapis/google-cloud-python/blob/main/packages/google-cloud-cloudcontrolspartner/noxfile.py + + +********** +Versioning +********** + +This library follows `Semantic Versioning`_. + +.. _Semantic Versioning: http://semver.org/ + +Some packages are currently in major version zero (``0.y.z``), which means that +anything may change at any time and the public API should not be considered +stable. + +****************************** +Contributor License Agreements +****************************** + +Before we can accept your pull requests you'll need to sign a Contributor +License Agreement (CLA): + +- **If you are an individual writing original source code** and **you own the + intellectual property**, then you'll need to sign an + `individual CLA `__. +- **If you work for a company that wants to allow you to contribute your work**, + then you'll need to sign a + `corporate CLA `__. + +You can sign these electronically (just scroll to the bottom). After that, +we'll be able to accept your pull requests. diff --git a/packages/google-cloud-cloudcontrolspartner/LICENSE b/packages/google-cloud-cloudcontrolspartner/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/packages/google-cloud-cloudcontrolspartner/MANIFEST.in b/packages/google-cloud-cloudcontrolspartner/MANIFEST.in new file mode 100644 index 000000000000..e0a66705318e --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/MANIFEST.in @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2023 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 +# +# https://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 by synthtool. DO NOT EDIT! +include README.rst LICENSE +recursive-include google *.json *.proto py.typed +recursive-include tests * +global-exclude *.py[co] +global-exclude __pycache__ + +# Exclude scripts for samples readmegen +prune scripts/readme-gen diff --git a/packages/google-cloud-cloudcontrolspartner/README.rst b/packages/google-cloud-cloudcontrolspartner/README.rst new file mode 100644 index 000000000000..680a28909e3a --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/README.rst @@ -0,0 +1,108 @@ +Python Client for Cloud Controls Partner API +============================================ + +|preview| |pypi| |versions| + +`Cloud Controls Partner API`_: Provides insights about your customers and their Assured Workloads based on your Sovereign Controls by Partners offering. + +- `Client Library Documentation`_ +- `Product Documentation`_ + +.. |preview| image:: https://img.shields.io/badge/support-preview-orange.svg + :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#stability-levels +.. |pypi| image:: https://img.shields.io/pypi/v/google-cloud-cloudcontrolspartner.svg + :target: https://pypi.org/project/google-cloud-cloudcontrolspartner/ +.. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-cloudcontrolspartner.svg + :target: https://pypi.org/project/google-cloud-cloudcontrolspartner/ +.. _Cloud Controls Partner API: https://cloud.google.com/sovereign-controls-by-partners/docs/sovereign-partners/reference/rest +.. _Client Library Documentation: https://cloud.google.com/python/docs/reference/google-cloud-cloudcontrolspartner/latest +.. _Product Documentation: https://cloud.google.com/sovereign-controls-by-partners/docs/sovereign-partners/reference/rest + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. `Enable the Cloud Controls Partner API.`_ +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Enable the Cloud Controls Partner API.: https://cloud.google.com/sovereign-controls-by-partners/docs/sovereign-partners/reference/rest +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a virtual environment using `venv`_. `venv`_ is a tool that +creates isolated Python environments. These isolated environments can have separate +versions of Python packages, which allows you to isolate one project's dependencies +from the dependencies of other projects. + +With `venv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`venv`: https://docs.python.org/3/library/venv.html + + +Code samples and snippets +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Code samples and snippets live in the `samples/`_ folder. + +.. _samples/: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-cloudcontrolspartner/samples + + +Supported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^ +Our client libraries are compatible with all current `active`_ and `maintenance`_ versions of +Python. + +Python >= 3.7 + +.. _active: https://devguide.python.org/devcycle/#in-development-main-branch +.. _maintenance: https://devguide.python.org/devcycle/#maintenance-branches + +Unsupported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Python <= 3.6 + +If you are using an `end-of-life`_ +version of Python, we recommend that you update as soon as possible to an actively supported version. + +.. _end-of-life: https://devguide.python.org/devcycle/#end-of-life-branches + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + pip install google-cloud-cloudcontrolspartner + + +Windows +^^^^^^^ + +.. code-block:: console + + py -m venv + .\\Scripts\activate + pip install google-cloud-cloudcontrolspartner + +Next Steps +~~~~~~~~~~ + +- Read the `Client Library Documentation`_ for Cloud Controls Partner API + to see other available methods on the client. +- Read the `Cloud Controls Partner API Product documentation`_ to learn + more about the product and see How-to Guides. +- View this `README`_ to see the full list of Cloud + APIs that we cover. + +.. _Cloud Controls Partner API Product documentation: https://cloud.google.com/sovereign-controls-by-partners/docs/sovereign-partners/reference/rest +.. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst diff --git a/packages/google-cloud-cloudcontrolspartner/docs/CHANGELOG.md b/packages/google-cloud-cloudcontrolspartner/docs/CHANGELOG.md new file mode 120000 index 000000000000..04c99a55caae --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/docs/CHANGELOG.md @@ -0,0 +1 @@ +../CHANGELOG.md \ No newline at end of file diff --git a/packages/google-cloud-cloudcontrolspartner/docs/README.rst b/packages/google-cloud-cloudcontrolspartner/docs/README.rst new file mode 120000 index 000000000000..89a0106941ff --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/docs/README.rst @@ -0,0 +1 @@ +../README.rst \ No newline at end of file diff --git a/packages/google-cloud-cloudcontrolspartner/docs/_static/custom.css b/packages/google-cloud-cloudcontrolspartner/docs/_static/custom.css new file mode 100644 index 000000000000..b0a295464b23 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/docs/_static/custom.css @@ -0,0 +1,20 @@ +div#python2-eol { + border-color: red; + border-width: medium; +} + +/* Ensure minimum width for 'Parameters' / 'Returns' column */ +dl.field-list > dt { + min-width: 100px +} + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/packages/google-cloud-cloudcontrolspartner/docs/_templates/layout.html b/packages/google-cloud-cloudcontrolspartner/docs/_templates/layout.html new file mode 100644 index 000000000000..6316a537f72b --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/docs/_templates/layout.html @@ -0,0 +1,50 @@ + +{% extends "!layout.html" %} +{%- block content %} +{%- if theme_fixed_sidebar|lower == 'true' %} +
+ {{ sidebar() }} + {%- block document %} +
+ {%- if render_sidebar %} +
+ {%- endif %} + + {%- block relbar_top %} + {%- if theme_show_relbar_top|tobool %} + + {%- endif %} + {% endblock %} + +
+
+ As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please + visit Python 2 support on Google Cloud. +
+ {% block body %} {% endblock %} +
+ + {%- block relbar_bottom %} + {%- if theme_show_relbar_bottom|tobool %} + + {%- endif %} + {% endblock %} + + {%- if render_sidebar %} +
+ {%- endif %} +
+ {%- endblock %} +
+
+{%- else %} +{{ super() }} +{%- endif %} +{%- endblock %} diff --git a/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1/cloud_controls_partner_core.rst b/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1/cloud_controls_partner_core.rst new file mode 100644 index 000000000000..db1df2c139ad --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1/cloud_controls_partner_core.rst @@ -0,0 +1,10 @@ +CloudControlsPartnerCore +------------------------------------------ + +.. automodule:: google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_core + :members: + :inherited-members: + +.. automodule:: google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_core.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1/cloud_controls_partner_monitoring.rst b/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1/cloud_controls_partner_monitoring.rst new file mode 100644 index 000000000000..771a3ece7431 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1/cloud_controls_partner_monitoring.rst @@ -0,0 +1,10 @@ +CloudControlsPartnerMonitoring +------------------------------------------------ + +.. automodule:: google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_monitoring + :members: + :inherited-members: + +.. automodule:: google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_monitoring.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1/services_.rst b/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1/services_.rst new file mode 100644 index 000000000000..b3fff740bf5e --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1/services_.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Cloudcontrolspartner v1 API +===================================================== +.. toctree:: + :maxdepth: 2 + + cloud_controls_partner_core + cloud_controls_partner_monitoring diff --git a/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1/types_.rst b/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1/types_.rst new file mode 100644 index 000000000000..585903f896ba --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Cloudcontrolspartner v1 API +================================================== + +.. automodule:: google.cloud.cloudcontrolspartner_v1.types + :members: + :show-inheritance: diff --git a/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1beta/cloud_controls_partner_core.rst b/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1beta/cloud_controls_partner_core.rst new file mode 100644 index 000000000000..50449432d5d9 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1beta/cloud_controls_partner_core.rst @@ -0,0 +1,10 @@ +CloudControlsPartnerCore +------------------------------------------ + +.. automodule:: google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core + :members: + :inherited-members: + +.. automodule:: google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1beta/cloud_controls_partner_monitoring.rst b/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1beta/cloud_controls_partner_monitoring.rst new file mode 100644 index 000000000000..4ce8b469e40e --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1beta/cloud_controls_partner_monitoring.rst @@ -0,0 +1,10 @@ +CloudControlsPartnerMonitoring +------------------------------------------------ + +.. automodule:: google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_monitoring + :members: + :inherited-members: + +.. automodule:: google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_monitoring.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1beta/services_.rst b/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1beta/services_.rst new file mode 100644 index 000000000000..7bba3628d026 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1beta/services_.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Cloudcontrolspartner v1beta API +========================================================= +.. toctree:: + :maxdepth: 2 + + cloud_controls_partner_core + cloud_controls_partner_monitoring diff --git a/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1beta/types_.rst b/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1beta/types_.rst new file mode 100644 index 000000000000..9af6a30854fb --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/docs/cloudcontrolspartner_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Cloudcontrolspartner v1beta API +====================================================== + +.. automodule:: google.cloud.cloudcontrolspartner_v1beta.types + :members: + :show-inheritance: diff --git a/packages/google-cloud-cloudcontrolspartner/docs/conf.py b/packages/google-cloud-cloudcontrolspartner/docs/conf.py new file mode 100644 index 000000000000..23e8f5f41625 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/docs/conf.py @@ -0,0 +1,384 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# +# google-cloud-cloudcontrolspartner documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import os +import shlex +import sys + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + +__version__ = "" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.5.5" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.doctest", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", + "recommonmark", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_options = {"members": True} +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = "google-cloud-cloudcontrolspartner" +copyright = "2019, Google" +author = "Google APIs" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [ + "_build", + "**/.nox/**/*", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for google-cloud-cloudcontrolspartner", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-cloudcontrolspartner-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + #'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + #'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + #'preamble': '', + # Latex figure (float) alignment + #'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-cloudcontrolspartner.tex", + "google-cloud-cloudcontrolspartner Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-cloudcontrolspartner", + "google-cloud-cloudcontrolspartner Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-cloudcontrolspartner", + "google-cloud-cloudcontrolspartner Documentation", + author, + "google-cloud-cloudcontrolspartner", + "google-cloud-cloudcontrolspartner Library", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), + "google.api_core": ( + "https://googleapis.dev/python/google-api-core/latest/", + None, + ), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/packages/google-cloud-cloudcontrolspartner/docs/index.rst b/packages/google-cloud-cloudcontrolspartner/docs/index.rst new file mode 100644 index 000000000000..e0bcac40bf8b --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/docs/index.rst @@ -0,0 +1,34 @@ +.. include:: README.rst + +.. include:: multiprocessing.rst + +This package includes clients for multiple versions of Cloud Controls Partner API. +By default, you will get version ``cloudcontrolspartner_v1``. + + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + cloudcontrolspartner_v1/services_ + cloudcontrolspartner_v1/types_ + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + cloudcontrolspartner_v1beta/services_ + cloudcontrolspartner_v1beta/types_ + + +Changelog +--------- + +For a list of all ``google-cloud-cloudcontrolspartner`` releases: + +.. toctree:: + :maxdepth: 2 + + CHANGELOG diff --git a/packages/google-cloud-cloudcontrolspartner/docs/multiprocessing.rst b/packages/google-cloud-cloudcontrolspartner/docs/multiprocessing.rst new file mode 100644 index 000000000000..536d17b2ea65 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/docs/multiprocessing.rst @@ -0,0 +1,7 @@ +.. note:: + + Because this client uses :mod:`grpc` library, it is safe to + share instances across threads. In multiprocessing scenarios, the best + practice is to create client instances *after* the invocation of + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or + :class:`multiprocessing.Process`. diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner/__init__.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner/__init__.py new file mode 100644 index 000000000000..058b708c4fdb --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner/__init__.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 google.cloud.cloudcontrolspartner import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_core.async_client import ( + CloudControlsPartnerCoreAsyncClient, +) +from google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_core.client import ( + CloudControlsPartnerCoreClient, +) +from google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_monitoring.async_client import ( + CloudControlsPartnerMonitoringAsyncClient, +) +from google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_monitoring.client import ( + CloudControlsPartnerMonitoringClient, +) +from google.cloud.cloudcontrolspartner_v1.types.access_approval_requests import ( + AccessApprovalRequest, + AccessReason, + ListAccessApprovalRequestsRequest, + ListAccessApprovalRequestsResponse, +) +from google.cloud.cloudcontrolspartner_v1.types.completion_state import CompletionState +from google.cloud.cloudcontrolspartner_v1.types.core import OperationMetadata +from google.cloud.cloudcontrolspartner_v1.types.customer_workloads import ( + GetWorkloadRequest, + ListWorkloadsRequest, + ListWorkloadsResponse, + Workload, + WorkloadOnboardingState, + WorkloadOnboardingStep, +) +from google.cloud.cloudcontrolspartner_v1.types.customers import ( + Customer, + CustomerOnboardingState, + CustomerOnboardingStep, + GetCustomerRequest, + ListCustomersRequest, + ListCustomersResponse, +) +from google.cloud.cloudcontrolspartner_v1.types.ekm_connections import ( + EkmConnection, + EkmConnections, + GetEkmConnectionsRequest, +) +from google.cloud.cloudcontrolspartner_v1.types.partner_permissions import ( + GetPartnerPermissionsRequest, + PartnerPermissions, +) +from google.cloud.cloudcontrolspartner_v1.types.partners import ( + EkmMetadata, + GetPartnerRequest, + Partner, + Sku, +) +from google.cloud.cloudcontrolspartner_v1.types.violations import ( + GetViolationRequest, + ListViolationsRequest, + ListViolationsResponse, + Violation, +) + +__all__ = ( + "CloudControlsPartnerCoreClient", + "CloudControlsPartnerCoreAsyncClient", + "CloudControlsPartnerMonitoringClient", + "CloudControlsPartnerMonitoringAsyncClient", + "AccessApprovalRequest", + "AccessReason", + "ListAccessApprovalRequestsRequest", + "ListAccessApprovalRequestsResponse", + "CompletionState", + "OperationMetadata", + "GetWorkloadRequest", + "ListWorkloadsRequest", + "ListWorkloadsResponse", + "Workload", + "WorkloadOnboardingState", + "WorkloadOnboardingStep", + "Customer", + "CustomerOnboardingState", + "CustomerOnboardingStep", + "GetCustomerRequest", + "ListCustomersRequest", + "ListCustomersResponse", + "EkmConnection", + "EkmConnections", + "GetEkmConnectionsRequest", + "GetPartnerPermissionsRequest", + "PartnerPermissions", + "EkmMetadata", + "GetPartnerRequest", + "Partner", + "Sku", + "GetViolationRequest", + "ListViolationsRequest", + "ListViolationsResponse", + "Violation", +) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner/gapic_version.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner/gapic_version.py new file mode 100644 index 000000000000..a7d39deb7a45 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner/py.typed b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner/py.typed new file mode 100644 index 000000000000..ff1c04426ba7 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-cloudcontrolspartner package uses inline types. diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/__init__.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/__init__.py new file mode 100644 index 000000000000..e133a2ec51b6 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/__init__.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 google.cloud.cloudcontrolspartner_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.cloud_controls_partner_core import ( + CloudControlsPartnerCoreAsyncClient, + CloudControlsPartnerCoreClient, +) +from .services.cloud_controls_partner_monitoring import ( + CloudControlsPartnerMonitoringAsyncClient, + CloudControlsPartnerMonitoringClient, +) +from .types.access_approval_requests import ( + AccessApprovalRequest, + AccessReason, + ListAccessApprovalRequestsRequest, + ListAccessApprovalRequestsResponse, +) +from .types.completion_state import CompletionState +from .types.core import OperationMetadata +from .types.customer_workloads import ( + GetWorkloadRequest, + ListWorkloadsRequest, + ListWorkloadsResponse, + Workload, + WorkloadOnboardingState, + WorkloadOnboardingStep, +) +from .types.customers import ( + Customer, + CustomerOnboardingState, + CustomerOnboardingStep, + GetCustomerRequest, + ListCustomersRequest, + ListCustomersResponse, +) +from .types.ekm_connections import ( + EkmConnection, + EkmConnections, + GetEkmConnectionsRequest, +) +from .types.partner_permissions import GetPartnerPermissionsRequest, PartnerPermissions +from .types.partners import EkmMetadata, GetPartnerRequest, Partner, Sku +from .types.violations import ( + GetViolationRequest, + ListViolationsRequest, + ListViolationsResponse, + Violation, +) + +__all__ = ( + "CloudControlsPartnerCoreAsyncClient", + "CloudControlsPartnerMonitoringAsyncClient", + "AccessApprovalRequest", + "AccessReason", + "CloudControlsPartnerCoreClient", + "CloudControlsPartnerMonitoringClient", + "CompletionState", + "Customer", + "CustomerOnboardingState", + "CustomerOnboardingStep", + "EkmConnection", + "EkmConnections", + "EkmMetadata", + "GetCustomerRequest", + "GetEkmConnectionsRequest", + "GetPartnerPermissionsRequest", + "GetPartnerRequest", + "GetViolationRequest", + "GetWorkloadRequest", + "ListAccessApprovalRequestsRequest", + "ListAccessApprovalRequestsResponse", + "ListCustomersRequest", + "ListCustomersResponse", + "ListViolationsRequest", + "ListViolationsResponse", + "ListWorkloadsRequest", + "ListWorkloadsResponse", + "OperationMetadata", + "Partner", + "PartnerPermissions", + "Sku", + "Violation", + "Workload", + "WorkloadOnboardingState", + "WorkloadOnboardingStep", +) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/gapic_metadata.json b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/gapic_metadata.json new file mode 100644 index 000000000000..1b7abd31cd1f --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/gapic_metadata.json @@ -0,0 +1,197 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.cloudcontrolspartner_v1", + "protoPackage": "google.cloud.cloudcontrolspartner.v1", + "schema": "1.0", + "services": { + "CloudControlsPartnerCore": { + "clients": { + "grpc": { + "libraryClient": "CloudControlsPartnerCoreClient", + "rpcs": { + "GetCustomer": { + "methods": [ + "get_customer" + ] + }, + "GetEkmConnections": { + "methods": [ + "get_ekm_connections" + ] + }, + "GetPartner": { + "methods": [ + "get_partner" + ] + }, + "GetPartnerPermissions": { + "methods": [ + "get_partner_permissions" + ] + }, + "GetWorkload": { + "methods": [ + "get_workload" + ] + }, + "ListAccessApprovalRequests": { + "methods": [ + "list_access_approval_requests" + ] + }, + "ListCustomers": { + "methods": [ + "list_customers" + ] + }, + "ListWorkloads": { + "methods": [ + "list_workloads" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CloudControlsPartnerCoreAsyncClient", + "rpcs": { + "GetCustomer": { + "methods": [ + "get_customer" + ] + }, + "GetEkmConnections": { + "methods": [ + "get_ekm_connections" + ] + }, + "GetPartner": { + "methods": [ + "get_partner" + ] + }, + "GetPartnerPermissions": { + "methods": [ + "get_partner_permissions" + ] + }, + "GetWorkload": { + "methods": [ + "get_workload" + ] + }, + "ListAccessApprovalRequests": { + "methods": [ + "list_access_approval_requests" + ] + }, + "ListCustomers": { + "methods": [ + "list_customers" + ] + }, + "ListWorkloads": { + "methods": [ + "list_workloads" + ] + } + } + }, + "rest": { + "libraryClient": "CloudControlsPartnerCoreClient", + "rpcs": { + "GetCustomer": { + "methods": [ + "get_customer" + ] + }, + "GetEkmConnections": { + "methods": [ + "get_ekm_connections" + ] + }, + "GetPartner": { + "methods": [ + "get_partner" + ] + }, + "GetPartnerPermissions": { + "methods": [ + "get_partner_permissions" + ] + }, + "GetWorkload": { + "methods": [ + "get_workload" + ] + }, + "ListAccessApprovalRequests": { + "methods": [ + "list_access_approval_requests" + ] + }, + "ListCustomers": { + "methods": [ + "list_customers" + ] + }, + "ListWorkloads": { + "methods": [ + "list_workloads" + ] + } + } + } + } + }, + "CloudControlsPartnerMonitoring": { + "clients": { + "grpc": { + "libraryClient": "CloudControlsPartnerMonitoringClient", + "rpcs": { + "GetViolation": { + "methods": [ + "get_violation" + ] + }, + "ListViolations": { + "methods": [ + "list_violations" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CloudControlsPartnerMonitoringAsyncClient", + "rpcs": { + "GetViolation": { + "methods": [ + "get_violation" + ] + }, + "ListViolations": { + "methods": [ + "list_violations" + ] + } + } + }, + "rest": { + "libraryClient": "CloudControlsPartnerMonitoringClient", + "rpcs": { + "GetViolation": { + "methods": [ + "get_violation" + ] + }, + "ListViolations": { + "methods": [ + "list_violations" + ] + } + } + } + } + } + } +} 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 new file mode 100644 index 000000000000..a7d39deb7a45 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/py.typed b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/py.typed new file mode 100644 index 000000000000..ff1c04426ba7 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-cloudcontrolspartner package uses inline types. diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/__init__.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/__init__.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/__init__.py new file mode 100644 index 000000000000..46206aebecfd --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .async_client import CloudControlsPartnerCoreAsyncClient +from .client import CloudControlsPartnerCoreClient + +__all__ = ( + "CloudControlsPartnerCoreClient", + "CloudControlsPartnerCoreAsyncClient", +) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/async_client.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/async_client.py new file mode 100644 index 000000000000..c9415648df54 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/async_client.py @@ -0,0 +1,1253 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.cloudcontrolspartner_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_core import ( + pagers, +) +from google.cloud.cloudcontrolspartner_v1.types import ( + access_approval_requests, + customer_workloads, + customers, + ekm_connections, + partner_permissions, + partners, +) + +from .client import CloudControlsPartnerCoreClient +from .transports.base import DEFAULT_CLIENT_INFO, CloudControlsPartnerCoreTransport +from .transports.grpc_asyncio import CloudControlsPartnerCoreGrpcAsyncIOTransport + + +class CloudControlsPartnerCoreAsyncClient: + """Service describing handlers for resources""" + + _client: CloudControlsPartnerCoreClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = CloudControlsPartnerCoreClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CloudControlsPartnerCoreClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ( + CloudControlsPartnerCoreClient._DEFAULT_ENDPOINT_TEMPLATE + ) + _DEFAULT_UNIVERSE = CloudControlsPartnerCoreClient._DEFAULT_UNIVERSE + + access_approval_request_path = staticmethod( + CloudControlsPartnerCoreClient.access_approval_request_path + ) + parse_access_approval_request_path = staticmethod( + CloudControlsPartnerCoreClient.parse_access_approval_request_path + ) + customer_path = staticmethod(CloudControlsPartnerCoreClient.customer_path) + parse_customer_path = staticmethod( + CloudControlsPartnerCoreClient.parse_customer_path + ) + ekm_connections_path = staticmethod( + CloudControlsPartnerCoreClient.ekm_connections_path + ) + parse_ekm_connections_path = staticmethod( + CloudControlsPartnerCoreClient.parse_ekm_connections_path + ) + partner_path = staticmethod(CloudControlsPartnerCoreClient.partner_path) + parse_partner_path = staticmethod(CloudControlsPartnerCoreClient.parse_partner_path) + partner_permissions_path = staticmethod( + CloudControlsPartnerCoreClient.partner_permissions_path + ) + parse_partner_permissions_path = staticmethod( + CloudControlsPartnerCoreClient.parse_partner_permissions_path + ) + workload_path = staticmethod(CloudControlsPartnerCoreClient.workload_path) + parse_workload_path = staticmethod( + CloudControlsPartnerCoreClient.parse_workload_path + ) + common_billing_account_path = staticmethod( + CloudControlsPartnerCoreClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + CloudControlsPartnerCoreClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(CloudControlsPartnerCoreClient.common_folder_path) + parse_common_folder_path = staticmethod( + CloudControlsPartnerCoreClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + CloudControlsPartnerCoreClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + CloudControlsPartnerCoreClient.parse_common_organization_path + ) + common_project_path = staticmethod( + CloudControlsPartnerCoreClient.common_project_path + ) + parse_common_project_path = staticmethod( + CloudControlsPartnerCoreClient.parse_common_project_path + ) + common_location_path = staticmethod( + CloudControlsPartnerCoreClient.common_location_path + ) + parse_common_location_path = staticmethod( + CloudControlsPartnerCoreClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudControlsPartnerCoreAsyncClient: The constructed client. + """ + return CloudControlsPartnerCoreClient.from_service_account_info.__func__(CloudControlsPartnerCoreAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudControlsPartnerCoreAsyncClient: The constructed client. + """ + return CloudControlsPartnerCoreClient.from_service_account_file.__func__(CloudControlsPartnerCoreAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CloudControlsPartnerCoreClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CloudControlsPartnerCoreTransport: + """Returns the transport used by the client instance. + + Returns: + CloudControlsPartnerCoreTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial( + type(CloudControlsPartnerCoreClient).get_transport_class, + type(CloudControlsPartnerCoreClient), + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CloudControlsPartnerCoreTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud controls partner core async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CloudControlsPartnerCoreTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CloudControlsPartnerCoreClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def get_workload( + self, + request: Optional[Union[customer_workloads.GetWorkloadRequest, 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]] = (), + ) -> customer_workloads.Workload: + r"""Gets details of a single workload + + .. 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 cloudcontrolspartner_v1 + + async def sample_get_workload(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetWorkloadRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workload(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1.types.GetWorkloadRequest, dict]]): + The request object. Message for getting a customer + workload. + name (:class:`str`): + Required. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + + 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.cloudcontrolspartner_v1.types.Workload: + Contains metadata around the [Workload + resource](\ https://cloud.google.com/assured-workloads/docs/reference/rest/Shared.Types/Workload) + in the Assured Workloads API. + + """ + # 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." + ) + + request = customer_workloads.GetWorkloadRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_workload, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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_workloads( + self, + request: Optional[Union[customer_workloads.ListWorkloadsRequest, 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.ListWorkloadsAsyncPager: + r"""Lists customer workloads for a given customer org id + + .. 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 cloudcontrolspartner_v1 + + async def sample_list_workloads(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.ListWorkloadsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workloads(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1.types.ListWorkloadsRequest, dict]]): + The request object. Request to list customer workloads. + parent (:class:`str`): + Required. Parent resource Format: + ``organizations/{organization}/locations/{location}/customers/{customer}`` + + 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.cloudcontrolspartner_v1.services.cloud_controls_partner_core.pagers.ListWorkloadsAsyncPager: + Response message for list customer + workloads requests. + 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." + ) + + request = customer_workloads.ListWorkloadsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_workloads, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListWorkloadsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_customer( + self, + request: Optional[Union[customers.GetCustomerRequest, 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]] = (), + ) -> customers.Customer: + r"""Gets details of a single customer + + .. 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 cloudcontrolspartner_v1 + + async def sample_get_customer(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetCustomerRequest( + name="name_value", + ) + + # Make the request + response = await client.get_customer(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1.types.GetCustomerRequest, dict]]): + The request object. Message for getting a customer + name (:class:`str`): + Required. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}`` + + 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.cloudcontrolspartner_v1.types.Customer: + Contains metadata around a Cloud + Controls Partner Customer + + """ + # 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." + ) + + request = customers.GetCustomerRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_customer, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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_customers( + self, + request: Optional[Union[customers.ListCustomersRequest, 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.ListCustomersAsyncPager: + r"""Lists customers of a partner identified by its Google + Cloud organization ID + + .. 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 cloudcontrolspartner_v1 + + async def sample_list_customers(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.ListCustomersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_customers(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1.types.ListCustomersRequest, dict]]): + The request object. Request to list customers + parent (:class:`str`): + Required. Parent resource Format: + ``organizations/{organization}/locations/{location}`` + + 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.cloudcontrolspartner_v1.services.cloud_controls_partner_core.pagers.ListCustomersAsyncPager: + Response message for list customer + Customers requests + 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." + ) + + request = customers.ListCustomersRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_customers, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListCustomersAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_ekm_connections( + self, + request: Optional[Union[ekm_connections.GetEkmConnectionsRequest, 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]] = (), + ) -> ekm_connections.EkmConnections: + r"""Gets the EKM connections associated with a workload + + .. 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 cloudcontrolspartner_v1 + + async def sample_get_ekm_connections(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetEkmConnectionsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_ekm_connections(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1.types.GetEkmConnectionsRequest, dict]]): + The request object. Request for getting the EKM + connections associated with a workload + name (:class:`str`): + Required. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/ekmConnections`` + + 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.cloudcontrolspartner_v1.types.EkmConnections: + The EKM connections associated with a + workload + + """ + # 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." + ) + + request = ekm_connections.GetEkmConnectionsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_ekm_connections, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 get_partner_permissions( + self, + request: Optional[ + Union[partner_permissions.GetPartnerPermissionsRequest, 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]] = (), + ) -> partner_permissions.PartnerPermissions: + r"""Gets the partner permissions granted for a workload + + .. 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 cloudcontrolspartner_v1 + + async def sample_get_partner_permissions(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetPartnerPermissionsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_partner_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1.types.GetPartnerPermissionsRequest, dict]]): + The request object. Request for getting the partner + permissions granted for a workload + name (:class:`str`): + Required. Name of the resource to get in the format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/partnerPermissions`` + + 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.cloudcontrolspartner_v1.types.PartnerPermissions: + The permissions granted to the + partner for a workload + + """ + # 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." + ) + + request = partner_permissions.GetPartnerPermissionsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_partner_permissions, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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_access_approval_requests( + self, + request: Optional[ + Union[access_approval_requests.ListAccessApprovalRequestsRequest, 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.ListAccessApprovalRequestsAsyncPager: + r"""Lists access requests associated with a workload + + .. 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 cloudcontrolspartner_v1 + + async def sample_list_access_approval_requests(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.ListAccessApprovalRequestsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_access_approval_requests(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1.types.ListAccessApprovalRequestsRequest, dict]]): + The request object. Request for getting the access + requests associated with a workload. + parent (:class:`str`): + Required. Parent resource Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + + 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.cloudcontrolspartner_v1.services.cloud_controls_partner_core.pagers.ListAccessApprovalRequestsAsyncPager: + Response message for list access + requests. + 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." + ) + + request = access_approval_requests.ListAccessApprovalRequestsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_access_approval_requests, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListAccessApprovalRequestsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_partner( + self, + request: Optional[Union[partners.GetPartnerRequest, 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]] = (), + ) -> partners.Partner: + r"""Get details of a Partner. + + .. 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 cloudcontrolspartner_v1 + + async def sample_get_partner(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetPartnerRequest( + name="name_value", + ) + + # Make the request + response = await client.get_partner(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1.types.GetPartnerRequest, dict]]): + The request object. Message for getting a Partner + name (:class:`str`): + Required. Format: + ``organizations/{organization}/locations/{location}/partner`` + + 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.cloudcontrolspartner_v1.types.Partner: + Message describing Partner 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." + ) + + request = partners.GetPartnerRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_partner, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 __aenter__(self) -> "CloudControlsPartnerCoreAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("CloudControlsPartnerCoreAsyncClient",) 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 new file mode 100644 index 000000000000..283bbcf791de --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/client.py @@ -0,0 +1,1705 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.cloudcontrolspartner_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_core import ( + pagers, +) +from google.cloud.cloudcontrolspartner_v1.types import ( + access_approval_requests, + customer_workloads, + customers, + ekm_connections, + partner_permissions, + partners, +) + +from .transports.base import DEFAULT_CLIENT_INFO, CloudControlsPartnerCoreTransport +from .transports.grpc import CloudControlsPartnerCoreGrpcTransport +from .transports.grpc_asyncio import CloudControlsPartnerCoreGrpcAsyncIOTransport +from .transports.rest import CloudControlsPartnerCoreRestTransport + + +class CloudControlsPartnerCoreClientMeta(type): + """Metaclass for the CloudControlsPartnerCore client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[CloudControlsPartnerCoreTransport]] + _transport_registry["grpc"] = CloudControlsPartnerCoreGrpcTransport + _transport_registry["grpc_asyncio"] = CloudControlsPartnerCoreGrpcAsyncIOTransport + _transport_registry["rest"] = CloudControlsPartnerCoreRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[CloudControlsPartnerCoreTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CloudControlsPartnerCoreClient(metaclass=CloudControlsPartnerCoreClientMeta): + """Service describing handlers for resources""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "cloudcontrolspartner.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "cloudcontrolspartner.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudControlsPartnerCoreClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudControlsPartnerCoreClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CloudControlsPartnerCoreTransport: + """Returns the transport used by the client instance. + + Returns: + CloudControlsPartnerCoreTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def access_approval_request_path( + organization: str, + location: str, + customer: str, + workload: str, + access_approval_request: str, + ) -> str: + """Returns a fully-qualified access_approval_request string.""" + return "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/accessApprovalRequests/{access_approval_request}".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + access_approval_request=access_approval_request, + ) + + @staticmethod + def parse_access_approval_request_path(path: str) -> Dict[str, str]: + """Parses a access_approval_request path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/customers/(?P.+?)/workloads/(?P.+?)/accessApprovalRequests/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def customer_path( + organization: str, + location: str, + customer: str, + ) -> str: + """Returns a fully-qualified customer string.""" + return "organizations/{organization}/locations/{location}/customers/{customer}".format( + organization=organization, + location=location, + customer=customer, + ) + + @staticmethod + def parse_customer_path(path: str) -> Dict[str, str]: + """Parses a customer path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/customers/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def ekm_connections_path( + organization: str, + location: str, + customer: str, + workload: str, + ) -> str: + """Returns a fully-qualified ekm_connections string.""" + return "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/ekmConnections".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + ) + + @staticmethod + def parse_ekm_connections_path(path: str) -> Dict[str, str]: + """Parses a ekm_connections path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/customers/(?P.+?)/workloads/(?P.+?)/ekmConnections$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def partner_path( + organization: str, + location: str, + ) -> str: + """Returns a fully-qualified partner string.""" + return "organizations/{organization}/locations/{location}/partner".format( + organization=organization, + location=location, + ) + + @staticmethod + def parse_partner_path(path: str) -> Dict[str, str]: + """Parses a partner path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/partner$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def partner_permissions_path( + organization: str, + location: str, + customer: str, + workload: str, + ) -> str: + """Returns a fully-qualified partner_permissions string.""" + return "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/partnerPermissions".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + ) + + @staticmethod + def parse_partner_permissions_path(path: str) -> Dict[str, str]: + """Parses a partner_permissions path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/customers/(?P.+?)/workloads/(?P.+?)/partnerPermissions$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def workload_path( + organization: str, + location: str, + customer: str, + workload: str, + ) -> str: + """Returns a fully-qualified workload string.""" + return "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + ) + + @staticmethod + def parse_workload_path(path: str) -> Dict[str, str]: + """Parses a workload path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/customers/(?P.+?)/workloads/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = CloudControlsPartnerCoreClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = CloudControlsPartnerCoreClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + CloudControlsPartnerCoreClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = CloudControlsPartnerCoreClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + 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. + + Returns: + bool: True iff the configured universe domain is valid. + + 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 + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, CloudControlsPartnerCoreTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud controls partner core client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CloudControlsPartnerCoreTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = CloudControlsPartnerCoreClient._read_environment_variables() + self._client_cert_source = ( + CloudControlsPartnerCoreClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = CloudControlsPartnerCoreClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, CloudControlsPartnerCoreTransport) + if transport_provided: + # transport is a CloudControlsPartnerCoreTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(CloudControlsPartnerCoreTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or CloudControlsPartnerCoreClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + Transport = type(self).get_transport_class(cast(str, transport)) + self._transport = Transport( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def get_workload( + self, + request: Optional[Union[customer_workloads.GetWorkloadRequest, 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]] = (), + ) -> customer_workloads.Workload: + r"""Gets details of a single workload + + .. 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 cloudcontrolspartner_v1 + + def sample_get_workload(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetWorkloadRequest( + name="name_value", + ) + + # Make the request + response = client.get_workload(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1.types.GetWorkloadRequest, dict]): + The request object. Message for getting a customer + workload. + name (str): + Required. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + + 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.cloudcontrolspartner_v1.types.Workload: + Contains metadata around the [Workload + resource](\ https://cloud.google.com/assured-workloads/docs/reference/rest/Shared.Types/Workload) + in the Assured Workloads API. + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a customer_workloads.GetWorkloadRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, customer_workloads.GetWorkloadRequest): + request = customer_workloads.GetWorkloadRequest(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_workload] + + # 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_workloads( + self, + request: Optional[Union[customer_workloads.ListWorkloadsRequest, 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.ListWorkloadsPager: + r"""Lists customer workloads for a given customer org id + + .. 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 cloudcontrolspartner_v1 + + def sample_list_workloads(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.ListWorkloadsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workloads(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1.types.ListWorkloadsRequest, dict]): + The request object. Request to list customer workloads. + parent (str): + Required. Parent resource Format: + ``organizations/{organization}/locations/{location}/customers/{customer}`` + + 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.cloudcontrolspartner_v1.services.cloud_controls_partner_core.pagers.ListWorkloadsPager: + Response message for list customer + workloads requests. + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a customer_workloads.ListWorkloadsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, customer_workloads.ListWorkloadsRequest): + request = customer_workloads.ListWorkloadsRequest(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_workloads] + + # 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.ListWorkloadsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_customer( + self, + request: Optional[Union[customers.GetCustomerRequest, 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]] = (), + ) -> customers.Customer: + r"""Gets details of a single customer + + .. 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 cloudcontrolspartner_v1 + + def sample_get_customer(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetCustomerRequest( + name="name_value", + ) + + # Make the request + response = client.get_customer(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1.types.GetCustomerRequest, dict]): + The request object. Message for getting a customer + name (str): + Required. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}`` + + 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.cloudcontrolspartner_v1.types.Customer: + Contains metadata around a Cloud + Controls Partner Customer + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a customers.GetCustomerRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, customers.GetCustomerRequest): + request = customers.GetCustomerRequest(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_customer] + + # 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_customers( + self, + request: Optional[Union[customers.ListCustomersRequest, 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.ListCustomersPager: + r"""Lists customers of a partner identified by its Google + Cloud organization ID + + .. 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 cloudcontrolspartner_v1 + + def sample_list_customers(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.ListCustomersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_customers(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1.types.ListCustomersRequest, dict]): + The request object. Request to list customers + parent (str): + Required. Parent resource Format: + ``organizations/{organization}/locations/{location}`` + + 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.cloudcontrolspartner_v1.services.cloud_controls_partner_core.pagers.ListCustomersPager: + Response message for list customer + Customers requests + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a customers.ListCustomersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, customers.ListCustomersRequest): + request = customers.ListCustomersRequest(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_customers] + + # 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.ListCustomersPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_ekm_connections( + self, + request: Optional[Union[ekm_connections.GetEkmConnectionsRequest, 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]] = (), + ) -> ekm_connections.EkmConnections: + r"""Gets the EKM connections associated with a workload + + .. 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 cloudcontrolspartner_v1 + + def sample_get_ekm_connections(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetEkmConnectionsRequest( + name="name_value", + ) + + # Make the request + response = client.get_ekm_connections(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1.types.GetEkmConnectionsRequest, dict]): + The request object. Request for getting the EKM + connections associated with a workload + name (str): + Required. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/ekmConnections`` + + 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.cloudcontrolspartner_v1.types.EkmConnections: + The EKM connections associated with a + workload + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a ekm_connections.GetEkmConnectionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, ekm_connections.GetEkmConnectionsRequest): + request = ekm_connections.GetEkmConnectionsRequest(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_ekm_connections] + + # 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 get_partner_permissions( + self, + request: Optional[ + Union[partner_permissions.GetPartnerPermissionsRequest, 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]] = (), + ) -> partner_permissions.PartnerPermissions: + r"""Gets the partner permissions granted for a workload + + .. 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 cloudcontrolspartner_v1 + + def sample_get_partner_permissions(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetPartnerPermissionsRequest( + name="name_value", + ) + + # Make the request + response = client.get_partner_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1.types.GetPartnerPermissionsRequest, dict]): + The request object. Request for getting the partner + permissions granted for a workload + name (str): + Required. Name of the resource to get in the format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/partnerPermissions`` + + 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.cloudcontrolspartner_v1.types.PartnerPermissions: + The permissions granted to the + partner for a workload + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a partner_permissions.GetPartnerPermissionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, partner_permissions.GetPartnerPermissionsRequest): + request = partner_permissions.GetPartnerPermissionsRequest(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_partner_permissions] + + # 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_access_approval_requests( + self, + request: Optional[ + Union[access_approval_requests.ListAccessApprovalRequestsRequest, 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.ListAccessApprovalRequestsPager: + r"""Lists access requests associated with a workload + + .. 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 cloudcontrolspartner_v1 + + def sample_list_access_approval_requests(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.ListAccessApprovalRequestsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_access_approval_requests(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1.types.ListAccessApprovalRequestsRequest, dict]): + The request object. Request for getting the access + requests associated with a workload. + parent (str): + Required. Parent resource Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + + 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.cloudcontrolspartner_v1.services.cloud_controls_partner_core.pagers.ListAccessApprovalRequestsPager: + Response message for list access + requests. + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a access_approval_requests.ListAccessApprovalRequestsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, access_approval_requests.ListAccessApprovalRequestsRequest + ): + request = access_approval_requests.ListAccessApprovalRequestsRequest( + 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_access_approval_requests + ] + + # 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.ListAccessApprovalRequestsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_partner( + self, + request: Optional[Union[partners.GetPartnerRequest, 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]] = (), + ) -> partners.Partner: + r"""Get details of a Partner. + + .. 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 cloudcontrolspartner_v1 + + def sample_get_partner(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetPartnerRequest( + name="name_value", + ) + + # Make the request + response = client.get_partner(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1.types.GetPartnerRequest, dict]): + The request object. Message for getting a Partner + name (str): + Required. Format: + ``organizations/{organization}/locations/{location}/partner`` + + 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.cloudcontrolspartner_v1.types.Partner: + Message describing Partner 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a partners.GetPartnerRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, partners.GetPartnerRequest): + request = partners.GetPartnerRequest(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_partner] + + # 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 __enter__(self) -> "CloudControlsPartnerCoreClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("CloudControlsPartnerCoreClient",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/pagers.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/pagers.py new file mode 100644 index 000000000000..3059121ecec9 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/pagers.py @@ -0,0 +1,429 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.cloudcontrolspartner_v1.types import ( + access_approval_requests, + customer_workloads, + customers, +) + + +class ListWorkloadsPager: + """A pager for iterating through ``list_workloads`` requests. + + This class thinly wraps an initial + :class:`google.cloud.cloudcontrolspartner_v1.types.ListWorkloadsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workloads`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkloads`` requests and continue to iterate + through the ``workloads`` field on the + corresponding responses. + + All the usual :class:`google.cloud.cloudcontrolspartner_v1.types.ListWorkloadsResponse` + 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[..., customer_workloads.ListWorkloadsResponse], + request: customer_workloads.ListWorkloadsRequest, + response: customer_workloads.ListWorkloadsResponse, + *, + 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.cloudcontrolspartner_v1.types.ListWorkloadsRequest): + The initial request object. + response (google.cloud.cloudcontrolspartner_v1.types.ListWorkloadsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = customer_workloads.ListWorkloadsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[customer_workloads.ListWorkloadsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[customer_workloads.Workload]: + for page in self.pages: + yield from page.workloads + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListWorkloadsAsyncPager: + """A pager for iterating through ``list_workloads`` requests. + + This class thinly wraps an initial + :class:`google.cloud.cloudcontrolspartner_v1.types.ListWorkloadsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workloads`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkloads`` requests and continue to iterate + through the ``workloads`` field on the + corresponding responses. + + All the usual :class:`google.cloud.cloudcontrolspartner_v1.types.ListWorkloadsResponse` + 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[customer_workloads.ListWorkloadsResponse]], + request: customer_workloads.ListWorkloadsRequest, + response: customer_workloads.ListWorkloadsResponse, + *, + 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.cloudcontrolspartner_v1.types.ListWorkloadsRequest): + The initial request object. + response (google.cloud.cloudcontrolspartner_v1.types.ListWorkloadsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = customer_workloads.ListWorkloadsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[customer_workloads.ListWorkloadsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[customer_workloads.Workload]: + async def async_generator(): + async for page in self.pages: + for response in page.workloads: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListCustomersPager: + """A pager for iterating through ``list_customers`` requests. + + This class thinly wraps an initial + :class:`google.cloud.cloudcontrolspartner_v1.types.ListCustomersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``customers`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCustomers`` requests and continue to iterate + through the ``customers`` field on the + corresponding responses. + + All the usual :class:`google.cloud.cloudcontrolspartner_v1.types.ListCustomersResponse` + 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[..., customers.ListCustomersResponse], + request: customers.ListCustomersRequest, + response: customers.ListCustomersResponse, + *, + 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.cloudcontrolspartner_v1.types.ListCustomersRequest): + The initial request object. + response (google.cloud.cloudcontrolspartner_v1.types.ListCustomersResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = customers.ListCustomersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[customers.ListCustomersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[customers.Customer]: + for page in self.pages: + yield from page.customers + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListCustomersAsyncPager: + """A pager for iterating through ``list_customers`` requests. + + This class thinly wraps an initial + :class:`google.cloud.cloudcontrolspartner_v1.types.ListCustomersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``customers`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCustomers`` requests and continue to iterate + through the ``customers`` field on the + corresponding responses. + + All the usual :class:`google.cloud.cloudcontrolspartner_v1.types.ListCustomersResponse` + 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[customers.ListCustomersResponse]], + request: customers.ListCustomersRequest, + response: customers.ListCustomersResponse, + *, + 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.cloudcontrolspartner_v1.types.ListCustomersRequest): + The initial request object. + response (google.cloud.cloudcontrolspartner_v1.types.ListCustomersResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = customers.ListCustomersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[customers.ListCustomersResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[customers.Customer]: + async def async_generator(): + async for page in self.pages: + for response in page.customers: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAccessApprovalRequestsPager: + """A pager for iterating through ``list_access_approval_requests`` requests. + + This class thinly wraps an initial + :class:`google.cloud.cloudcontrolspartner_v1.types.ListAccessApprovalRequestsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``access_approval_requests`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAccessApprovalRequests`` requests and continue to iterate + through the ``access_approval_requests`` field on the + corresponding responses. + + All the usual :class:`google.cloud.cloudcontrolspartner_v1.types.ListAccessApprovalRequestsResponse` + 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[ + ..., access_approval_requests.ListAccessApprovalRequestsResponse + ], + request: access_approval_requests.ListAccessApprovalRequestsRequest, + response: access_approval_requests.ListAccessApprovalRequestsResponse, + *, + 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.cloudcontrolspartner_v1.types.ListAccessApprovalRequestsRequest): + The initial request object. + response (google.cloud.cloudcontrolspartner_v1.types.ListAccessApprovalRequestsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = access_approval_requests.ListAccessApprovalRequestsRequest( + request + ) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[access_approval_requests.ListAccessApprovalRequestsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[access_approval_requests.AccessApprovalRequest]: + for page in self.pages: + yield from page.access_approval_requests + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAccessApprovalRequestsAsyncPager: + """A pager for iterating through ``list_access_approval_requests`` requests. + + This class thinly wraps an initial + :class:`google.cloud.cloudcontrolspartner_v1.types.ListAccessApprovalRequestsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``access_approval_requests`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAccessApprovalRequests`` requests and continue to iterate + through the ``access_approval_requests`` field on the + corresponding responses. + + All the usual :class:`google.cloud.cloudcontrolspartner_v1.types.ListAccessApprovalRequestsResponse` + 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[access_approval_requests.ListAccessApprovalRequestsResponse] + ], + request: access_approval_requests.ListAccessApprovalRequestsRequest, + response: access_approval_requests.ListAccessApprovalRequestsResponse, + *, + 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.cloudcontrolspartner_v1.types.ListAccessApprovalRequestsRequest): + The initial request object. + response (google.cloud.cloudcontrolspartner_v1.types.ListAccessApprovalRequestsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = access_approval_requests.ListAccessApprovalRequestsRequest( + request + ) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[access_approval_requests.ListAccessApprovalRequestsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterator[access_approval_requests.AccessApprovalRequest]: + async def async_generator(): + async for page in self.pages: + for response in page.access_approval_requests: + 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-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/transports/__init__.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/transports/__init__.py new file mode 100644 index 000000000000..932a6f5d3fd5 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/transports/__init__.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CloudControlsPartnerCoreTransport +from .grpc import CloudControlsPartnerCoreGrpcTransport +from .grpc_asyncio import CloudControlsPartnerCoreGrpcAsyncIOTransport +from .rest import ( + CloudControlsPartnerCoreRestInterceptor, + CloudControlsPartnerCoreRestTransport, +) + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[CloudControlsPartnerCoreTransport]] +_transport_registry["grpc"] = CloudControlsPartnerCoreGrpcTransport +_transport_registry["grpc_asyncio"] = CloudControlsPartnerCoreGrpcAsyncIOTransport +_transport_registry["rest"] = CloudControlsPartnerCoreRestTransport + +__all__ = ( + "CloudControlsPartnerCoreTransport", + "CloudControlsPartnerCoreGrpcTransport", + "CloudControlsPartnerCoreGrpcAsyncIOTransport", + "CloudControlsPartnerCoreRestTransport", + "CloudControlsPartnerCoreRestInterceptor", +) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/transports/base.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/transports/base.py new file mode 100644 index 000000000000..9f5baf424f9c --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/transports/base.py @@ -0,0 +1,340 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.cloudcontrolspartner_v1 import gapic_version as package_version +from google.cloud.cloudcontrolspartner_v1.types import ( + access_approval_requests, + customer_workloads, + customers, + ekm_connections, + partner_permissions, + partners, +) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class CloudControlsPartnerCoreTransport(abc.ABC): + """Abstract transport class for CloudControlsPartnerCore.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "cloudcontrolspartner.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudcontrolspartner.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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_workload: gapic_v1.method.wrap_method( + self.get_workload, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_workloads: gapic_v1.method.wrap_method( + self.list_workloads, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_customer: gapic_v1.method.wrap_method( + self.get_customer, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_customers: gapic_v1.method.wrap_method( + self.list_customers, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_ekm_connections: gapic_v1.method.wrap_method( + self.get_ekm_connections, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_partner_permissions: gapic_v1.method.wrap_method( + self.get_partner_permissions, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_access_approval_requests: gapic_v1.method.wrap_method( + self.list_access_approval_requests, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_partner: gapic_v1.method.wrap_method( + self.get_partner, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_workload( + self, + ) -> Callable[ + [customer_workloads.GetWorkloadRequest], + Union[customer_workloads.Workload, Awaitable[customer_workloads.Workload]], + ]: + raise NotImplementedError() + + @property + def list_workloads( + self, + ) -> Callable[ + [customer_workloads.ListWorkloadsRequest], + Union[ + customer_workloads.ListWorkloadsResponse, + Awaitable[customer_workloads.ListWorkloadsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_customer( + self, + ) -> Callable[ + [customers.GetCustomerRequest], + Union[customers.Customer, Awaitable[customers.Customer]], + ]: + raise NotImplementedError() + + @property + def list_customers( + self, + ) -> Callable[ + [customers.ListCustomersRequest], + Union[ + customers.ListCustomersResponse, Awaitable[customers.ListCustomersResponse] + ], + ]: + raise NotImplementedError() + + @property + def get_ekm_connections( + self, + ) -> Callable[ + [ekm_connections.GetEkmConnectionsRequest], + Union[ + ekm_connections.EkmConnections, Awaitable[ekm_connections.EkmConnections] + ], + ]: + raise NotImplementedError() + + @property + def get_partner_permissions( + self, + ) -> Callable[ + [partner_permissions.GetPartnerPermissionsRequest], + Union[ + partner_permissions.PartnerPermissions, + Awaitable[partner_permissions.PartnerPermissions], + ], + ]: + raise NotImplementedError() + + @property + def list_access_approval_requests( + self, + ) -> Callable[ + [access_approval_requests.ListAccessApprovalRequestsRequest], + Union[ + access_approval_requests.ListAccessApprovalRequestsResponse, + Awaitable[access_approval_requests.ListAccessApprovalRequestsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_partner( + self, + ) -> Callable[ + [partners.GetPartnerRequest], + Union[partners.Partner, Awaitable[partners.Partner]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("CloudControlsPartnerCoreTransport",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/transports/grpc.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/transports/grpc.py new file mode 100644 index 000000000000..19e4e442d4ff --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/transports/grpc.py @@ -0,0 +1,466 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import grpc # type: ignore + +from google.cloud.cloudcontrolspartner_v1.types import ( + access_approval_requests, + customer_workloads, + customers, + ekm_connections, + partner_permissions, + partners, +) + +from .base import DEFAULT_CLIENT_INFO, CloudControlsPartnerCoreTransport + + +class CloudControlsPartnerCoreGrpcTransport(CloudControlsPartnerCoreTransport): + """gRPC backend transport for CloudControlsPartnerCore. + + Service describing handlers for resources + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "cloudcontrolspartner.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudcontrolspartner.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. + This argument is ignored if ``channel`` is provided. + 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. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "cloudcontrolspartner.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def get_workload( + self, + ) -> Callable[[customer_workloads.GetWorkloadRequest], customer_workloads.Workload]: + r"""Return a callable for the get workload method over gRPC. + + Gets details of a single workload + + Returns: + Callable[[~.GetWorkloadRequest], + ~.Workload]: + 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_workload" not in self._stubs: + self._stubs["get_workload"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore/GetWorkload", + request_serializer=customer_workloads.GetWorkloadRequest.serialize, + response_deserializer=customer_workloads.Workload.deserialize, + ) + return self._stubs["get_workload"] + + @property + def list_workloads( + self, + ) -> Callable[ + [customer_workloads.ListWorkloadsRequest], + customer_workloads.ListWorkloadsResponse, + ]: + r"""Return a callable for the list workloads method over gRPC. + + Lists customer workloads for a given customer org id + + Returns: + Callable[[~.ListWorkloadsRequest], + ~.ListWorkloadsResponse]: + 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_workloads" not in self._stubs: + self._stubs["list_workloads"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore/ListWorkloads", + request_serializer=customer_workloads.ListWorkloadsRequest.serialize, + response_deserializer=customer_workloads.ListWorkloadsResponse.deserialize, + ) + return self._stubs["list_workloads"] + + @property + def get_customer( + self, + ) -> Callable[[customers.GetCustomerRequest], customers.Customer]: + r"""Return a callable for the get customer method over gRPC. + + Gets details of a single customer + + Returns: + Callable[[~.GetCustomerRequest], + ~.Customer]: + 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_customer" not in self._stubs: + self._stubs["get_customer"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore/GetCustomer", + request_serializer=customers.GetCustomerRequest.serialize, + response_deserializer=customers.Customer.deserialize, + ) + return self._stubs["get_customer"] + + @property + def list_customers( + self, + ) -> Callable[[customers.ListCustomersRequest], customers.ListCustomersResponse]: + r"""Return a callable for the list customers method over gRPC. + + Lists customers of a partner identified by its Google + Cloud organization ID + + Returns: + Callable[[~.ListCustomersRequest], + ~.ListCustomersResponse]: + 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_customers" not in self._stubs: + self._stubs["list_customers"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore/ListCustomers", + request_serializer=customers.ListCustomersRequest.serialize, + response_deserializer=customers.ListCustomersResponse.deserialize, + ) + return self._stubs["list_customers"] + + @property + def get_ekm_connections( + self, + ) -> Callable[ + [ekm_connections.GetEkmConnectionsRequest], ekm_connections.EkmConnections + ]: + r"""Return a callable for the get ekm connections method over gRPC. + + Gets the EKM connections associated with a workload + + Returns: + Callable[[~.GetEkmConnectionsRequest], + ~.EkmConnections]: + 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_ekm_connections" not in self._stubs: + self._stubs["get_ekm_connections"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore/GetEkmConnections", + request_serializer=ekm_connections.GetEkmConnectionsRequest.serialize, + response_deserializer=ekm_connections.EkmConnections.deserialize, + ) + return self._stubs["get_ekm_connections"] + + @property + def get_partner_permissions( + self, + ) -> Callable[ + [partner_permissions.GetPartnerPermissionsRequest], + partner_permissions.PartnerPermissions, + ]: + r"""Return a callable for the get partner permissions method over gRPC. + + Gets the partner permissions granted for a workload + + Returns: + Callable[[~.GetPartnerPermissionsRequest], + ~.PartnerPermissions]: + 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_partner_permissions" not in self._stubs: + self._stubs["get_partner_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore/GetPartnerPermissions", + request_serializer=partner_permissions.GetPartnerPermissionsRequest.serialize, + response_deserializer=partner_permissions.PartnerPermissions.deserialize, + ) + return self._stubs["get_partner_permissions"] + + @property + def list_access_approval_requests( + self, + ) -> Callable[ + [access_approval_requests.ListAccessApprovalRequestsRequest], + access_approval_requests.ListAccessApprovalRequestsResponse, + ]: + r"""Return a callable for the list access approval requests method over gRPC. + + Lists access requests associated with a workload + + Returns: + Callable[[~.ListAccessApprovalRequestsRequest], + ~.ListAccessApprovalRequestsResponse]: + 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_access_approval_requests" not in self._stubs: + self._stubs[ + "list_access_approval_requests" + ] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore/ListAccessApprovalRequests", + request_serializer=access_approval_requests.ListAccessApprovalRequestsRequest.serialize, + response_deserializer=access_approval_requests.ListAccessApprovalRequestsResponse.deserialize, + ) + return self._stubs["list_access_approval_requests"] + + @property + def get_partner(self) -> Callable[[partners.GetPartnerRequest], partners.Partner]: + r"""Return a callable for the get partner method over gRPC. + + Get details of a Partner. + + Returns: + Callable[[~.GetPartnerRequest], + ~.Partner]: + 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_partner" not in self._stubs: + self._stubs["get_partner"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore/GetPartner", + request_serializer=partners.GetPartnerRequest.serialize, + response_deserializer=partners.Partner.deserialize, + ) + return self._stubs["get_partner"] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("CloudControlsPartnerCoreGrpcTransport",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/transports/grpc_asyncio.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/transports/grpc_asyncio.py new file mode 100644 index 000000000000..1c199b5676ca --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/transports/grpc_asyncio.py @@ -0,0 +1,472 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.cloudcontrolspartner_v1.types import ( + access_approval_requests, + customer_workloads, + customers, + ekm_connections, + partner_permissions, + partners, +) + +from .base import DEFAULT_CLIENT_INFO, CloudControlsPartnerCoreTransport +from .grpc import CloudControlsPartnerCoreGrpcTransport + + +class CloudControlsPartnerCoreGrpcAsyncIOTransport(CloudControlsPartnerCoreTransport): + """gRPC AsyncIO backend transport for CloudControlsPartnerCore. + + Service describing handlers for resources + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "cloudcontrolspartner.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudcontrolspartner.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudcontrolspartner.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. + This argument is ignored if ``channel`` is provided. + 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_workload( + self, + ) -> Callable[ + [customer_workloads.GetWorkloadRequest], Awaitable[customer_workloads.Workload] + ]: + r"""Return a callable for the get workload method over gRPC. + + Gets details of a single workload + + Returns: + Callable[[~.GetWorkloadRequest], + Awaitable[~.Workload]]: + 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_workload" not in self._stubs: + self._stubs["get_workload"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore/GetWorkload", + request_serializer=customer_workloads.GetWorkloadRequest.serialize, + response_deserializer=customer_workloads.Workload.deserialize, + ) + return self._stubs["get_workload"] + + @property + def list_workloads( + self, + ) -> Callable[ + [customer_workloads.ListWorkloadsRequest], + Awaitable[customer_workloads.ListWorkloadsResponse], + ]: + r"""Return a callable for the list workloads method over gRPC. + + Lists customer workloads for a given customer org id + + Returns: + Callable[[~.ListWorkloadsRequest], + Awaitable[~.ListWorkloadsResponse]]: + 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_workloads" not in self._stubs: + self._stubs["list_workloads"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore/ListWorkloads", + request_serializer=customer_workloads.ListWorkloadsRequest.serialize, + response_deserializer=customer_workloads.ListWorkloadsResponse.deserialize, + ) + return self._stubs["list_workloads"] + + @property + def get_customer( + self, + ) -> Callable[[customers.GetCustomerRequest], Awaitable[customers.Customer]]: + r"""Return a callable for the get customer method over gRPC. + + Gets details of a single customer + + Returns: + Callable[[~.GetCustomerRequest], + Awaitable[~.Customer]]: + 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_customer" not in self._stubs: + self._stubs["get_customer"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore/GetCustomer", + request_serializer=customers.GetCustomerRequest.serialize, + response_deserializer=customers.Customer.deserialize, + ) + return self._stubs["get_customer"] + + @property + def list_customers( + self, + ) -> Callable[ + [customers.ListCustomersRequest], Awaitable[customers.ListCustomersResponse] + ]: + r"""Return a callable for the list customers method over gRPC. + + Lists customers of a partner identified by its Google + Cloud organization ID + + Returns: + Callable[[~.ListCustomersRequest], + Awaitable[~.ListCustomersResponse]]: + 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_customers" not in self._stubs: + self._stubs["list_customers"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore/ListCustomers", + request_serializer=customers.ListCustomersRequest.serialize, + response_deserializer=customers.ListCustomersResponse.deserialize, + ) + return self._stubs["list_customers"] + + @property + def get_ekm_connections( + self, + ) -> Callable[ + [ekm_connections.GetEkmConnectionsRequest], + Awaitable[ekm_connections.EkmConnections], + ]: + r"""Return a callable for the get ekm connections method over gRPC. + + Gets the EKM connections associated with a workload + + Returns: + Callable[[~.GetEkmConnectionsRequest], + Awaitable[~.EkmConnections]]: + 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_ekm_connections" not in self._stubs: + self._stubs["get_ekm_connections"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore/GetEkmConnections", + request_serializer=ekm_connections.GetEkmConnectionsRequest.serialize, + response_deserializer=ekm_connections.EkmConnections.deserialize, + ) + return self._stubs["get_ekm_connections"] + + @property + def get_partner_permissions( + self, + ) -> Callable[ + [partner_permissions.GetPartnerPermissionsRequest], + Awaitable[partner_permissions.PartnerPermissions], + ]: + r"""Return a callable for the get partner permissions method over gRPC. + + Gets the partner permissions granted for a workload + + Returns: + Callable[[~.GetPartnerPermissionsRequest], + Awaitable[~.PartnerPermissions]]: + 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_partner_permissions" not in self._stubs: + self._stubs["get_partner_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore/GetPartnerPermissions", + request_serializer=partner_permissions.GetPartnerPermissionsRequest.serialize, + response_deserializer=partner_permissions.PartnerPermissions.deserialize, + ) + return self._stubs["get_partner_permissions"] + + @property + def list_access_approval_requests( + self, + ) -> Callable[ + [access_approval_requests.ListAccessApprovalRequestsRequest], + Awaitable[access_approval_requests.ListAccessApprovalRequestsResponse], + ]: + r"""Return a callable for the list access approval requests method over gRPC. + + Lists access requests associated with a workload + + Returns: + Callable[[~.ListAccessApprovalRequestsRequest], + Awaitable[~.ListAccessApprovalRequestsResponse]]: + 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_access_approval_requests" not in self._stubs: + self._stubs[ + "list_access_approval_requests" + ] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore/ListAccessApprovalRequests", + request_serializer=access_approval_requests.ListAccessApprovalRequestsRequest.serialize, + response_deserializer=access_approval_requests.ListAccessApprovalRequestsResponse.deserialize, + ) + return self._stubs["list_access_approval_requests"] + + @property + def get_partner( + self, + ) -> Callable[[partners.GetPartnerRequest], Awaitable[partners.Partner]]: + r"""Return a callable for the get partner method over gRPC. + + Get details of a Partner. + + Returns: + Callable[[~.GetPartnerRequest], + Awaitable[~.Partner]]: + 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_partner" not in self._stubs: + self._stubs["get_partner"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore/GetPartner", + request_serializer=partners.GetPartnerRequest.serialize, + response_deserializer=partners.Partner.deserialize, + ) + return self._stubs["get_partner"] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ("CloudControlsPartnerCoreGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/transports/rest.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/transports/rest.py new file mode 100644 index 000000000000..cbe605dce992 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_core/transports/rest.py @@ -0,0 +1,1212 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.cloudcontrolspartner_v1.types import ( + access_approval_requests, + customer_workloads, + customers, + ekm_connections, + partner_permissions, + partners, +) + +from .base import CloudControlsPartnerCoreTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class CloudControlsPartnerCoreRestInterceptor: + """Interceptor for CloudControlsPartnerCore. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the CloudControlsPartnerCoreRestTransport. + + .. code-block:: python + class MyCustomCloudControlsPartnerCoreInterceptor(CloudControlsPartnerCoreRestInterceptor): + def pre_get_customer(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_customer(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_ekm_connections(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_ekm_connections(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_partner(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_partner(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_partner_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_partner_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_workload(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_workload(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_access_approval_requests(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_access_approval_requests(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_customers(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_customers(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workloads(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workloads(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CloudControlsPartnerCoreRestTransport(interceptor=MyCustomCloudControlsPartnerCoreInterceptor()) + client = CloudControlsPartnerCoreClient(transport=transport) + + + """ + + def pre_get_customer( + self, request: customers.GetCustomerRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[customers.GetCustomerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_customer + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerCore server. + """ + return request, metadata + + def post_get_customer(self, response: customers.Customer) -> customers.Customer: + """Post-rpc interceptor for get_customer + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerCore server but before + it is returned to user code. + """ + return response + + def pre_get_ekm_connections( + self, + request: ekm_connections.GetEkmConnectionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ekm_connections.GetEkmConnectionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_ekm_connections + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerCore server. + """ + return request, metadata + + def post_get_ekm_connections( + self, response: ekm_connections.EkmConnections + ) -> ekm_connections.EkmConnections: + """Post-rpc interceptor for get_ekm_connections + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerCore server but before + it is returned to user code. + """ + return response + + def pre_get_partner( + self, request: partners.GetPartnerRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[partners.GetPartnerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_partner + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerCore server. + """ + return request, metadata + + def post_get_partner(self, response: partners.Partner) -> partners.Partner: + """Post-rpc interceptor for get_partner + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerCore server but before + it is returned to user code. + """ + return response + + def pre_get_partner_permissions( + self, + request: partner_permissions.GetPartnerPermissionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + partner_permissions.GetPartnerPermissionsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for get_partner_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerCore server. + """ + return request, metadata + + def post_get_partner_permissions( + self, response: partner_permissions.PartnerPermissions + ) -> partner_permissions.PartnerPermissions: + """Post-rpc interceptor for get_partner_permissions + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerCore server but before + it is returned to user code. + """ + return response + + def pre_get_workload( + self, + request: customer_workloads.GetWorkloadRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[customer_workloads.GetWorkloadRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_workload + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerCore server. + """ + return request, metadata + + def post_get_workload( + self, response: customer_workloads.Workload + ) -> customer_workloads.Workload: + """Post-rpc interceptor for get_workload + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerCore server but before + it is returned to user code. + """ + return response + + def pre_list_access_approval_requests( + self, + request: access_approval_requests.ListAccessApprovalRequestsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + access_approval_requests.ListAccessApprovalRequestsRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for list_access_approval_requests + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerCore server. + """ + return request, metadata + + def post_list_access_approval_requests( + self, response: access_approval_requests.ListAccessApprovalRequestsResponse + ) -> access_approval_requests.ListAccessApprovalRequestsResponse: + """Post-rpc interceptor for list_access_approval_requests + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerCore server but before + it is returned to user code. + """ + return response + + def pre_list_customers( + self, + request: customers.ListCustomersRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[customers.ListCustomersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_customers + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerCore server. + """ + return request, metadata + + def post_list_customers( + self, response: customers.ListCustomersResponse + ) -> customers.ListCustomersResponse: + """Post-rpc interceptor for list_customers + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerCore server but before + it is returned to user code. + """ + return response + + def pre_list_workloads( + self, + request: customer_workloads.ListWorkloadsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[customer_workloads.ListWorkloadsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_workloads + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerCore server. + """ + return request, metadata + + def post_list_workloads( + self, response: customer_workloads.ListWorkloadsResponse + ) -> customer_workloads.ListWorkloadsResponse: + """Post-rpc interceptor for list_workloads + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerCore server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class CloudControlsPartnerCoreRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CloudControlsPartnerCoreRestInterceptor + + +class CloudControlsPartnerCoreRestTransport(CloudControlsPartnerCoreTransport): + """REST backend transport for CloudControlsPartnerCore. + + Service describing handlers for resources + + 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 = "cloudcontrolspartner.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[CloudControlsPartnerCoreRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudcontrolspartner.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 + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or CloudControlsPartnerCoreRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetCustomer(CloudControlsPartnerCoreRestStub): + def __hash__(self): + return hash("GetCustomer") + + __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 + } + + def __call__( + self, + request: customers.GetCustomerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> customers.Customer: + r"""Call the get customer method over HTTP. + + Args: + request (~.customers.GetCustomerRequest): + The request object. Message for getting a customer + 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: + ~.customers.Customer: + Contains metadata around a Cloud + Controls Partner Customer + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/customers/*}", + }, + ] + request, metadata = self._interceptor.pre_get_customer(request, metadata) + pb_request = customers.GetCustomerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = customers.Customer() + pb_resp = customers.Customer.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_customer(resp) + return resp + + class _GetEkmConnections(CloudControlsPartnerCoreRestStub): + def __hash__(self): + return hash("GetEkmConnections") + + __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 + } + + def __call__( + self, + request: ekm_connections.GetEkmConnectionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_connections.EkmConnections: + r"""Call the get ekm connections method over HTTP. + + Args: + request (~.ekm_connections.GetEkmConnectionsRequest): + The request object. Request for getting the EKM + connections associated with a workload + 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: + ~.ekm_connections.EkmConnections: + The EKM connections associated with a + workload + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/customers/*/workloads/*/ekmConnections}", + }, + ] + request, metadata = self._interceptor.pre_get_ekm_connections( + request, metadata + ) + pb_request = ekm_connections.GetEkmConnectionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = ekm_connections.EkmConnections() + pb_resp = ekm_connections.EkmConnections.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_ekm_connections(resp) + return resp + + class _GetPartner(CloudControlsPartnerCoreRestStub): + def __hash__(self): + return hash("GetPartner") + + __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 + } + + def __call__( + self, + request: partners.GetPartnerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> partners.Partner: + r"""Call the get partner method over HTTP. + + Args: + request (~.partners.GetPartnerRequest): + The request object. Message for getting a Partner + 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: + ~.partners.Partner: + Message describing Partner resource + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/partner}", + }, + ] + request, metadata = self._interceptor.pre_get_partner(request, metadata) + pb_request = partners.GetPartnerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = partners.Partner() + pb_resp = partners.Partner.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_partner(resp) + return resp + + class _GetPartnerPermissions(CloudControlsPartnerCoreRestStub): + def __hash__(self): + return hash("GetPartnerPermissions") + + __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 + } + + def __call__( + self, + request: partner_permissions.GetPartnerPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> partner_permissions.PartnerPermissions: + r"""Call the get partner permissions method over HTTP. + + Args: + request (~.partner_permissions.GetPartnerPermissionsRequest): + The request object. Request for getting the partner + permissions granted for a workload + 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: + ~.partner_permissions.PartnerPermissions: + The permissions granted to the + partner for a workload + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/customers/*/workloads/*/partnerPermissions}", + }, + ] + request, metadata = self._interceptor.pre_get_partner_permissions( + request, metadata + ) + pb_request = partner_permissions.GetPartnerPermissionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = partner_permissions.PartnerPermissions() + pb_resp = partner_permissions.PartnerPermissions.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_partner_permissions(resp) + return resp + + class _GetWorkload(CloudControlsPartnerCoreRestStub): + def __hash__(self): + return hash("GetWorkload") + + __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 + } + + def __call__( + self, + request: customer_workloads.GetWorkloadRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> customer_workloads.Workload: + r"""Call the get workload method over HTTP. + + Args: + request (~.customer_workloads.GetWorkloadRequest): + The request object. Message for getting a customer + workload. + 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: + ~.customer_workloads.Workload: + Contains metadata around the `Workload + resource `__ + in the Assured Workloads API. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/customers/*/workloads/*}", + }, + ] + request, metadata = self._interceptor.pre_get_workload(request, metadata) + pb_request = customer_workloads.GetWorkloadRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = customer_workloads.Workload() + pb_resp = customer_workloads.Workload.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_workload(resp) + return resp + + class _ListAccessApprovalRequests(CloudControlsPartnerCoreRestStub): + def __hash__(self): + return hash("ListAccessApprovalRequests") + + __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 + } + + def __call__( + self, + request: access_approval_requests.ListAccessApprovalRequestsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> access_approval_requests.ListAccessApprovalRequestsResponse: + r"""Call the list access approval + requests method over HTTP. + + Args: + request (~.access_approval_requests.ListAccessApprovalRequestsRequest): + The request object. Request for getting the access + requests associated with a workload. + 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: + ~.access_approval_requests.ListAccessApprovalRequestsResponse: + Response message for list access + requests. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=organizations/*/locations/*/customers/*/workloads/*}/accessApprovalRequests", + }, + ] + request, metadata = self._interceptor.pre_list_access_approval_requests( + request, metadata + ) + pb_request = access_approval_requests.ListAccessApprovalRequestsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = access_approval_requests.ListAccessApprovalRequestsResponse() + pb_resp = access_approval_requests.ListAccessApprovalRequestsResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_access_approval_requests(resp) + return resp + + class _ListCustomers(CloudControlsPartnerCoreRestStub): + def __hash__(self): + return hash("ListCustomers") + + __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 + } + + def __call__( + self, + request: customers.ListCustomersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> customers.ListCustomersResponse: + r"""Call the list customers method over HTTP. + + Args: + request (~.customers.ListCustomersRequest): + The request object. Request to list customers + 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: + ~.customers.ListCustomersResponse: + Response message for list customer + Customers requests + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=organizations/*/locations/*}/customers", + }, + ] + request, metadata = self._interceptor.pre_list_customers(request, metadata) + pb_request = customers.ListCustomersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = customers.ListCustomersResponse() + pb_resp = customers.ListCustomersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_customers(resp) + return resp + + class _ListWorkloads(CloudControlsPartnerCoreRestStub): + def __hash__(self): + return hash("ListWorkloads") + + __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 + } + + def __call__( + self, + request: customer_workloads.ListWorkloadsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> customer_workloads.ListWorkloadsResponse: + r"""Call the list workloads method over HTTP. + + Args: + request (~.customer_workloads.ListWorkloadsRequest): + The request object. Request to list customer workloads. + 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: + ~.customer_workloads.ListWorkloadsResponse: + Response message for list customer + workloads requests. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=organizations/*/locations/*/customers/*}/workloads", + }, + ] + request, metadata = self._interceptor.pre_list_workloads(request, metadata) + pb_request = customer_workloads.ListWorkloadsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = customer_workloads.ListWorkloadsResponse() + pb_resp = customer_workloads.ListWorkloadsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_workloads(resp) + return resp + + @property + def get_customer( + self, + ) -> Callable[[customers.GetCustomerRequest], customers.Customer]: + # 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._GetCustomer(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_ekm_connections( + self, + ) -> Callable[ + [ekm_connections.GetEkmConnectionsRequest], ekm_connections.EkmConnections + ]: + # 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._GetEkmConnections(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_partner(self) -> Callable[[partners.GetPartnerRequest], partners.Partner]: + # 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._GetPartner(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_partner_permissions( + self, + ) -> Callable[ + [partner_permissions.GetPartnerPermissionsRequest], + partner_permissions.PartnerPermissions, + ]: + # 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._GetPartnerPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_workload( + self, + ) -> Callable[[customer_workloads.GetWorkloadRequest], customer_workloads.Workload]: + # 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._GetWorkload(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_access_approval_requests( + self, + ) -> Callable[ + [access_approval_requests.ListAccessApprovalRequestsRequest], + access_approval_requests.ListAccessApprovalRequestsResponse, + ]: + # 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._ListAccessApprovalRequests(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_customers( + self, + ) -> Callable[[customers.ListCustomersRequest], customers.ListCustomersResponse]: + # 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._ListCustomers(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workloads( + self, + ) -> Callable[ + [customer_workloads.ListWorkloadsRequest], + customer_workloads.ListWorkloadsResponse, + ]: + # 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._ListWorkloads(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("CloudControlsPartnerCoreRestTransport",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/__init__.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/__init__.py new file mode 100644 index 000000000000..28b28fe9ff7f --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .async_client import CloudControlsPartnerMonitoringAsyncClient +from .client import CloudControlsPartnerMonitoringClient + +__all__ = ( + "CloudControlsPartnerMonitoringClient", + "CloudControlsPartnerMonitoringAsyncClient", +) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/async_client.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/async_client.py new file mode 100644 index 000000000000..f6bf801227b7 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/async_client.py @@ -0,0 +1,528 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.cloudcontrolspartner_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_monitoring import ( + pagers, +) +from google.cloud.cloudcontrolspartner_v1.types import violations + +from .client import CloudControlsPartnerMonitoringClient +from .transports.base import ( + DEFAULT_CLIENT_INFO, + CloudControlsPartnerMonitoringTransport, +) +from .transports.grpc_asyncio import CloudControlsPartnerMonitoringGrpcAsyncIOTransport + + +class CloudControlsPartnerMonitoringAsyncClient: + """Service describing handlers for resources""" + + _client: CloudControlsPartnerMonitoringClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = CloudControlsPartnerMonitoringClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CloudControlsPartnerMonitoringClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ( + CloudControlsPartnerMonitoringClient._DEFAULT_ENDPOINT_TEMPLATE + ) + _DEFAULT_UNIVERSE = CloudControlsPartnerMonitoringClient._DEFAULT_UNIVERSE + + violation_path = staticmethod(CloudControlsPartnerMonitoringClient.violation_path) + parse_violation_path = staticmethod( + CloudControlsPartnerMonitoringClient.parse_violation_path + ) + common_billing_account_path = staticmethod( + CloudControlsPartnerMonitoringClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + CloudControlsPartnerMonitoringClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + CloudControlsPartnerMonitoringClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + CloudControlsPartnerMonitoringClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + CloudControlsPartnerMonitoringClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + CloudControlsPartnerMonitoringClient.parse_common_organization_path + ) + common_project_path = staticmethod( + CloudControlsPartnerMonitoringClient.common_project_path + ) + parse_common_project_path = staticmethod( + CloudControlsPartnerMonitoringClient.parse_common_project_path + ) + common_location_path = staticmethod( + CloudControlsPartnerMonitoringClient.common_location_path + ) + parse_common_location_path = staticmethod( + CloudControlsPartnerMonitoringClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudControlsPartnerMonitoringAsyncClient: The constructed client. + """ + return CloudControlsPartnerMonitoringClient.from_service_account_info.__func__(CloudControlsPartnerMonitoringAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudControlsPartnerMonitoringAsyncClient: The constructed client. + """ + return CloudControlsPartnerMonitoringClient.from_service_account_file.__func__(CloudControlsPartnerMonitoringAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CloudControlsPartnerMonitoringClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CloudControlsPartnerMonitoringTransport: + """Returns the transport used by the client instance. + + Returns: + CloudControlsPartnerMonitoringTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial( + type(CloudControlsPartnerMonitoringClient).get_transport_class, + type(CloudControlsPartnerMonitoringClient), + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CloudControlsPartnerMonitoringTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud controls partner monitoring async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CloudControlsPartnerMonitoringTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CloudControlsPartnerMonitoringClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_violations( + self, + request: Optional[Union[violations.ListViolationsRequest, 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.ListViolationsAsyncPager: + r"""Lists Violations for a workload Callers may also choose to read + across multiple Customers or for a single customer as per + `AIP-159 `__ by using '-' (the + hyphen or dash character) as a wildcard character instead of + {customer} & {workload}. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + + .. 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 cloudcontrolspartner_v1 + + async def sample_list_violations(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerMonitoringAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.ListViolationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_violations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1.types.ListViolationsRequest, dict]]): + The request object. Message for requesting list of + Violations + parent (:class:`str`): + Required. Parent resource Format + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + + 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.cloudcontrolspartner_v1.services.cloud_controls_partner_monitoring.pagers.ListViolationsAsyncPager: + Response message for list customer + violation requests + 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." + ) + + request = violations.ListViolationsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_violations, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListViolationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_violation( + self, + request: Optional[Union[violations.GetViolationRequest, 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]] = (), + ) -> violations.Violation: + r"""Gets details of a single Violation. + + .. 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 cloudcontrolspartner_v1 + + async def sample_get_violation(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerMonitoringAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetViolationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_violation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1.types.GetViolationRequest, dict]]): + The request object. Message for getting a Violation + name (:class:`str`): + Required. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/violations/{violation}`` + + 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.cloudcontrolspartner_v1.types.Violation: + Details of resource Violation + """ + # 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." + ) + + request = violations.GetViolationRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_violation, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 __aenter__(self) -> "CloudControlsPartnerMonitoringAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("CloudControlsPartnerMonitoringAsyncClient",) 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 new file mode 100644 index 000000000000..ee569b5cb072 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/client.py @@ -0,0 +1,935 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.cloudcontrolspartner_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_monitoring import ( + pagers, +) +from google.cloud.cloudcontrolspartner_v1.types import violations + +from .transports.base import ( + DEFAULT_CLIENT_INFO, + CloudControlsPartnerMonitoringTransport, +) +from .transports.grpc import CloudControlsPartnerMonitoringGrpcTransport +from .transports.grpc_asyncio import CloudControlsPartnerMonitoringGrpcAsyncIOTransport +from .transports.rest import CloudControlsPartnerMonitoringRestTransport + + +class CloudControlsPartnerMonitoringClientMeta(type): + """Metaclass for the CloudControlsPartnerMonitoring client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[CloudControlsPartnerMonitoringTransport]] + _transport_registry["grpc"] = CloudControlsPartnerMonitoringGrpcTransport + _transport_registry[ + "grpc_asyncio" + ] = CloudControlsPartnerMonitoringGrpcAsyncIOTransport + _transport_registry["rest"] = CloudControlsPartnerMonitoringRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[CloudControlsPartnerMonitoringTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CloudControlsPartnerMonitoringClient( + metaclass=CloudControlsPartnerMonitoringClientMeta +): + """Service describing handlers for resources""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "cloudcontrolspartner.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "cloudcontrolspartner.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudControlsPartnerMonitoringClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudControlsPartnerMonitoringClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CloudControlsPartnerMonitoringTransport: + """Returns the transport used by the client instance. + + Returns: + CloudControlsPartnerMonitoringTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def violation_path( + organization: str, + location: str, + customer: str, + workload: str, + violation: str, + ) -> str: + """Returns a fully-qualified violation string.""" + return "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/violations/{violation}".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + violation=violation, + ) + + @staticmethod + def parse_violation_path(path: str) -> Dict[str, str]: + """Parses a violation path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/customers/(?P.+?)/workloads/(?P.+?)/violations/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = CloudControlsPartnerMonitoringClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = CloudControlsPartnerMonitoringClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + CloudControlsPartnerMonitoringClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = CloudControlsPartnerMonitoringClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + 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. + + Returns: + bool: True iff the configured universe domain is valid. + + 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 + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, CloudControlsPartnerMonitoringTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud controls partner monitoring client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CloudControlsPartnerMonitoringTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = CloudControlsPartnerMonitoringClient._read_environment_variables() + self._client_cert_source = ( + CloudControlsPartnerMonitoringClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = ( + CloudControlsPartnerMonitoringClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance( + transport, CloudControlsPartnerMonitoringTransport + ) + if transport_provided: + # transport is a CloudControlsPartnerMonitoringTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(CloudControlsPartnerMonitoringTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or CloudControlsPartnerMonitoringClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + Transport = type(self).get_transport_class(cast(str, transport)) + self._transport = Transport( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def list_violations( + self, + request: Optional[Union[violations.ListViolationsRequest, 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.ListViolationsPager: + r"""Lists Violations for a workload Callers may also choose to read + across multiple Customers or for a single customer as per + `AIP-159 `__ by using '-' (the + hyphen or dash character) as a wildcard character instead of + {customer} & {workload}. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + + .. 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 cloudcontrolspartner_v1 + + def sample_list_violations(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerMonitoringClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.ListViolationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_violations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1.types.ListViolationsRequest, dict]): + The request object. Message for requesting list of + Violations + parent (str): + Required. Parent resource Format + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + + 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.cloudcontrolspartner_v1.services.cloud_controls_partner_monitoring.pagers.ListViolationsPager: + Response message for list customer + violation requests + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a violations.ListViolationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, violations.ListViolationsRequest): + request = violations.ListViolationsRequest(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_violations] + + # 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.ListViolationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_violation( + self, + request: Optional[Union[violations.GetViolationRequest, 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]] = (), + ) -> violations.Violation: + r"""Gets details of a single Violation. + + .. 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 cloudcontrolspartner_v1 + + def sample_get_violation(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerMonitoringClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetViolationRequest( + name="name_value", + ) + + # Make the request + response = client.get_violation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1.types.GetViolationRequest, dict]): + The request object. Message for getting a Violation + name (str): + Required. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/violations/{violation}`` + + 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.cloudcontrolspartner_v1.types.Violation: + Details of resource Violation + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a violations.GetViolationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, violations.GetViolationRequest): + request = violations.GetViolationRequest(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_violation] + + # 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 __enter__(self) -> "CloudControlsPartnerMonitoringClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("CloudControlsPartnerMonitoringClient",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/pagers.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/pagers.py new file mode 100644 index 000000000000..dd111417b148 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/pagers.py @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.cloudcontrolspartner_v1.types import violations + + +class ListViolationsPager: + """A pager for iterating through ``list_violations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.cloudcontrolspartner_v1.types.ListViolationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``violations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListViolations`` requests and continue to iterate + through the ``violations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.cloudcontrolspartner_v1.types.ListViolationsResponse` + 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[..., violations.ListViolationsResponse], + request: violations.ListViolationsRequest, + response: violations.ListViolationsResponse, + *, + 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.cloudcontrolspartner_v1.types.ListViolationsRequest): + The initial request object. + response (google.cloud.cloudcontrolspartner_v1.types.ListViolationsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = violations.ListViolationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[violations.ListViolationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[violations.Violation]: + for page in self.pages: + yield from page.violations + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListViolationsAsyncPager: + """A pager for iterating through ``list_violations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.cloudcontrolspartner_v1.types.ListViolationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``violations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListViolations`` requests and continue to iterate + through the ``violations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.cloudcontrolspartner_v1.types.ListViolationsResponse` + 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[violations.ListViolationsResponse]], + request: violations.ListViolationsRequest, + response: violations.ListViolationsResponse, + *, + 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.cloudcontrolspartner_v1.types.ListViolationsRequest): + The initial request object. + response (google.cloud.cloudcontrolspartner_v1.types.ListViolationsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = violations.ListViolationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[violations.ListViolationsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[violations.Violation]: + async def async_generator(): + async for page in self.pages: + for response in page.violations: + 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-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/transports/__init__.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/transports/__init__.py new file mode 100644 index 000000000000..d8563cd63e93 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/transports/__init__.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CloudControlsPartnerMonitoringTransport +from .grpc import CloudControlsPartnerMonitoringGrpcTransport +from .grpc_asyncio import CloudControlsPartnerMonitoringGrpcAsyncIOTransport +from .rest import ( + CloudControlsPartnerMonitoringRestInterceptor, + CloudControlsPartnerMonitoringRestTransport, +) + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[CloudControlsPartnerMonitoringTransport]] +_transport_registry["grpc"] = CloudControlsPartnerMonitoringGrpcTransport +_transport_registry["grpc_asyncio"] = CloudControlsPartnerMonitoringGrpcAsyncIOTransport +_transport_registry["rest"] = CloudControlsPartnerMonitoringRestTransport + +__all__ = ( + "CloudControlsPartnerMonitoringTransport", + "CloudControlsPartnerMonitoringGrpcTransport", + "CloudControlsPartnerMonitoringGrpcAsyncIOTransport", + "CloudControlsPartnerMonitoringRestTransport", + "CloudControlsPartnerMonitoringRestInterceptor", +) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/transports/base.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/transports/base.py new file mode 100644 index 000000000000..cc3df7183a86 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/transports/base.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.cloudcontrolspartner_v1 import gapic_version as package_version +from google.cloud.cloudcontrolspartner_v1.types import violations + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class CloudControlsPartnerMonitoringTransport(abc.ABC): + """Abstract transport class for CloudControlsPartnerMonitoring.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "cloudcontrolspartner.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudcontrolspartner.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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_violations: gapic_v1.method.wrap_method( + self.list_violations, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_violation: gapic_v1.method.wrap_method( + self.get_violation, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_violations( + self, + ) -> Callable[ + [violations.ListViolationsRequest], + Union[ + violations.ListViolationsResponse, + Awaitable[violations.ListViolationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_violation( + self, + ) -> Callable[ + [violations.GetViolationRequest], + Union[violations.Violation, Awaitable[violations.Violation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("CloudControlsPartnerMonitoringTransport",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/transports/grpc.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/transports/grpc.py new file mode 100644 index 000000000000..cdc89af534da --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/transports/grpc.py @@ -0,0 +1,300 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import grpc # type: ignore + +from google.cloud.cloudcontrolspartner_v1.types import violations + +from .base import DEFAULT_CLIENT_INFO, CloudControlsPartnerMonitoringTransport + + +class CloudControlsPartnerMonitoringGrpcTransport( + CloudControlsPartnerMonitoringTransport +): + """gRPC backend transport for CloudControlsPartnerMonitoring. + + Service describing handlers for resources + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "cloudcontrolspartner.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudcontrolspartner.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. + This argument is ignored if ``channel`` is provided. + 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. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "cloudcontrolspartner.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def list_violations( + self, + ) -> Callable[ + [violations.ListViolationsRequest], violations.ListViolationsResponse + ]: + r"""Return a callable for the list violations method over gRPC. + + Lists Violations for a workload Callers may also choose to read + across multiple Customers or for a single customer as per + `AIP-159 `__ by using '-' (the + hyphen or dash character) as a wildcard character instead of + {customer} & {workload}. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + + Returns: + Callable[[~.ListViolationsRequest], + ~.ListViolationsResponse]: + 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_violations" not in self._stubs: + self._stubs["list_violations"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerMonitoring/ListViolations", + request_serializer=violations.ListViolationsRequest.serialize, + response_deserializer=violations.ListViolationsResponse.deserialize, + ) + return self._stubs["list_violations"] + + @property + def get_violation( + self, + ) -> Callable[[violations.GetViolationRequest], violations.Violation]: + r"""Return a callable for the get violation method over gRPC. + + Gets details of a single Violation. + + Returns: + Callable[[~.GetViolationRequest], + ~.Violation]: + 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_violation" not in self._stubs: + self._stubs["get_violation"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerMonitoring/GetViolation", + request_serializer=violations.GetViolationRequest.serialize, + response_deserializer=violations.Violation.deserialize, + ) + return self._stubs["get_violation"] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("CloudControlsPartnerMonitoringGrpcTransport",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/transports/grpc_asyncio.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/transports/grpc_asyncio.py new file mode 100644 index 000000000000..092f324a4071 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/transports/grpc_asyncio.py @@ -0,0 +1,299 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.cloudcontrolspartner_v1.types import violations + +from .base import DEFAULT_CLIENT_INFO, CloudControlsPartnerMonitoringTransport +from .grpc import CloudControlsPartnerMonitoringGrpcTransport + + +class CloudControlsPartnerMonitoringGrpcAsyncIOTransport( + CloudControlsPartnerMonitoringTransport +): + """gRPC AsyncIO backend transport for CloudControlsPartnerMonitoring. + + Service describing handlers for resources + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "cloudcontrolspartner.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudcontrolspartner.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudcontrolspartner.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. + This argument is ignored if ``channel`` is provided. + 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_violations( + self, + ) -> Callable[ + [violations.ListViolationsRequest], Awaitable[violations.ListViolationsResponse] + ]: + r"""Return a callable for the list violations method over gRPC. + + Lists Violations for a workload Callers may also choose to read + across multiple Customers or for a single customer as per + `AIP-159 `__ by using '-' (the + hyphen or dash character) as a wildcard character instead of + {customer} & {workload}. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + + Returns: + Callable[[~.ListViolationsRequest], + Awaitable[~.ListViolationsResponse]]: + 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_violations" not in self._stubs: + self._stubs["list_violations"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerMonitoring/ListViolations", + request_serializer=violations.ListViolationsRequest.serialize, + response_deserializer=violations.ListViolationsResponse.deserialize, + ) + return self._stubs["list_violations"] + + @property + def get_violation( + self, + ) -> Callable[[violations.GetViolationRequest], Awaitable[violations.Violation]]: + r"""Return a callable for the get violation method over gRPC. + + Gets details of a single Violation. + + Returns: + Callable[[~.GetViolationRequest], + Awaitable[~.Violation]]: + 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_violation" not in self._stubs: + self._stubs["get_violation"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerMonitoring/GetViolation", + request_serializer=violations.GetViolationRequest.serialize, + response_deserializer=violations.Violation.deserialize, + ) + return self._stubs["get_violation"] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ("CloudControlsPartnerMonitoringGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/transports/rest.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/transports/rest.py new file mode 100644 index 000000000000..51a0c7d8975d --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/services/cloud_controls_partner_monitoring/transports/rest.py @@ -0,0 +1,434 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.cloudcontrolspartner_v1.types import violations + +from .base import CloudControlsPartnerMonitoringTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class CloudControlsPartnerMonitoringRestInterceptor: + """Interceptor for CloudControlsPartnerMonitoring. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the CloudControlsPartnerMonitoringRestTransport. + + .. code-block:: python + class MyCustomCloudControlsPartnerMonitoringInterceptor(CloudControlsPartnerMonitoringRestInterceptor): + def pre_get_violation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_violation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_violations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_violations(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CloudControlsPartnerMonitoringRestTransport(interceptor=MyCustomCloudControlsPartnerMonitoringInterceptor()) + client = CloudControlsPartnerMonitoringClient(transport=transport) + + + """ + + def pre_get_violation( + self, + request: violations.GetViolationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[violations.GetViolationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_violation + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerMonitoring server. + """ + return request, metadata + + def post_get_violation( + self, response: violations.Violation + ) -> violations.Violation: + """Post-rpc interceptor for get_violation + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerMonitoring server but before + it is returned to user code. + """ + return response + + def pre_list_violations( + self, + request: violations.ListViolationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[violations.ListViolationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_violations + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerMonitoring server. + """ + return request, metadata + + def post_list_violations( + self, response: violations.ListViolationsResponse + ) -> violations.ListViolationsResponse: + """Post-rpc interceptor for list_violations + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerMonitoring server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class CloudControlsPartnerMonitoringRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CloudControlsPartnerMonitoringRestInterceptor + + +class CloudControlsPartnerMonitoringRestTransport( + CloudControlsPartnerMonitoringTransport +): + """REST backend transport for CloudControlsPartnerMonitoring. + + Service describing handlers for resources + + 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 = "cloudcontrolspartner.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[CloudControlsPartnerMonitoringRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudcontrolspartner.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 + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = ( + interceptor or CloudControlsPartnerMonitoringRestInterceptor() + ) + self._prep_wrapped_messages(client_info) + + class _GetViolation(CloudControlsPartnerMonitoringRestStub): + def __hash__(self): + return hash("GetViolation") + + __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 + } + + def __call__( + self, + request: violations.GetViolationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> violations.Violation: + r"""Call the get violation method over HTTP. + + Args: + request (~.violations.GetViolationRequest): + The request object. Message for getting a Violation + 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: + ~.violations.Violation: + Details of resource Violation + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/customers/*/workloads/*/violations/*}", + }, + ] + request, metadata = self._interceptor.pre_get_violation(request, metadata) + pb_request = violations.GetViolationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = violations.Violation() + pb_resp = violations.Violation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_violation(resp) + return resp + + class _ListViolations(CloudControlsPartnerMonitoringRestStub): + def __hash__(self): + return hash("ListViolations") + + __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 + } + + def __call__( + self, + request: violations.ListViolationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> violations.ListViolationsResponse: + r"""Call the list violations method over HTTP. + + Args: + request (~.violations.ListViolationsRequest): + The request object. Message for requesting list of + Violations + 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: + ~.violations.ListViolationsResponse: + Response message for list customer + violation requests + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=organizations/*/locations/*/customers/*/workloads/*}/violations", + }, + ] + request, metadata = self._interceptor.pre_list_violations(request, metadata) + pb_request = violations.ListViolationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = violations.ListViolationsResponse() + pb_resp = violations.ListViolationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_violations(resp) + return resp + + @property + def get_violation( + self, + ) -> Callable[[violations.GetViolationRequest], violations.Violation]: + # 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._GetViolation(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_violations( + self, + ) -> Callable[ + [violations.ListViolationsRequest], violations.ListViolationsResponse + ]: + # 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._ListViolations(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("CloudControlsPartnerMonitoringRestTransport",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/__init__.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/__init__.py new file mode 100644 index 000000000000..3a4f3a5a7d64 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/__init__.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .access_approval_requests import ( + AccessApprovalRequest, + AccessReason, + ListAccessApprovalRequestsRequest, + ListAccessApprovalRequestsResponse, +) +from .completion_state import CompletionState +from .core import OperationMetadata +from .customer_workloads import ( + GetWorkloadRequest, + ListWorkloadsRequest, + ListWorkloadsResponse, + Workload, + WorkloadOnboardingState, + WorkloadOnboardingStep, +) +from .customers import ( + Customer, + CustomerOnboardingState, + CustomerOnboardingStep, + GetCustomerRequest, + ListCustomersRequest, + ListCustomersResponse, +) +from .ekm_connections import EkmConnection, EkmConnections, GetEkmConnectionsRequest +from .partner_permissions import GetPartnerPermissionsRequest, PartnerPermissions +from .partners import EkmMetadata, GetPartnerRequest, Partner, Sku +from .violations import ( + GetViolationRequest, + ListViolationsRequest, + ListViolationsResponse, + Violation, +) + +__all__ = ( + "AccessApprovalRequest", + "AccessReason", + "ListAccessApprovalRequestsRequest", + "ListAccessApprovalRequestsResponse", + "CompletionState", + "OperationMetadata", + "GetWorkloadRequest", + "ListWorkloadsRequest", + "ListWorkloadsResponse", + "Workload", + "WorkloadOnboardingState", + "WorkloadOnboardingStep", + "Customer", + "CustomerOnboardingState", + "CustomerOnboardingStep", + "GetCustomerRequest", + "ListCustomersRequest", + "ListCustomersResponse", + "EkmConnection", + "EkmConnections", + "GetEkmConnectionsRequest", + "GetPartnerPermissionsRequest", + "PartnerPermissions", + "EkmMetadata", + "GetPartnerRequest", + "Partner", + "Sku", + "GetViolationRequest", + "ListViolationsRequest", + "ListViolationsResponse", + "Violation", +) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/access_approval_requests.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/access_approval_requests.py new file mode 100644 index 000000000000..da3343702e6b --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/access_approval_requests.py @@ -0,0 +1,228 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloudcontrolspartner.v1", + manifest={ + "AccessApprovalRequest", + "ListAccessApprovalRequestsRequest", + "ListAccessApprovalRequestsResponse", + "AccessReason", + }, +) + + +class AccessApprovalRequest(proto.Message): + r"""Details about the Access request. + + Attributes: + name (str): + Identifier. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/accessApprovalRequests/{access_approval_request}`` + request_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which approval was requested. + requested_reason (google.cloud.cloudcontrolspartner_v1.types.AccessReason): + The justification for which approval is being + requested. + requested_expiration_time (google.protobuf.timestamp_pb2.Timestamp): + The requested expiration for the approval. If + the request is approved, access will be granted + from the time of approval until the expiration + time. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + requested_reason: "AccessReason" = proto.Field( + proto.MESSAGE, + number=3, + message="AccessReason", + ) + requested_expiration_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class ListAccessApprovalRequestsRequest(proto.Message): + r"""Request for getting the access requests associated with a + workload. + + Attributes: + parent (str): + Required. Parent resource Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + page_size (int): + Optional. The maximum number of access + requests to return. The service may return fewer + than this value. If unspecified, at most 500 + access requests will be returned. + page_token (str): + Optional. A page token, received from a previous + ``ListAccessApprovalRequests`` call. Provide this to + retrieve the subsequent page. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + """ + + 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, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListAccessApprovalRequestsResponse(proto.Message): + r"""Response message for list access requests. + + Attributes: + access_approval_requests (MutableSequence[google.cloud.cloudcontrolspartner_v1.types.AccessApprovalRequest]): + List of access approval requests + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + access_approval_requests: MutableSequence[ + "AccessApprovalRequest" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AccessApprovalRequest", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class AccessReason(proto.Message): + r"""Reason for the access. + + Attributes: + type_ (google.cloud.cloudcontrolspartner_v1.types.AccessReason.Type): + Type of access justification. + detail (str): + More detail about certain reason types. See + comments for each type above. + """ + + class Type(proto.Enum): + r"""Type of access justification. + + Values: + TYPE_UNSPECIFIED (0): + Default value for proto, shouldn't be used. + CUSTOMER_INITIATED_SUPPORT (1): + Customer made a request or raised an issue that required the + principal to access customer data. ``detail`` is of the form + ("#####" is the issue ID): + + - "Feedback Report: #####" + - "Case Number: #####" + - "Case ID: #####" + - "E-PIN Reference: #####" + - "Google-#####" + - "T-#####". + GOOGLE_INITIATED_SERVICE (2): + The principal accessed customer data in order + to diagnose or resolve a suspected issue in + services. Often this access is used to confirm + that customers are not affected by a suspected + service issue or to remediate a reversible + system issue. + GOOGLE_INITIATED_REVIEW (3): + Google initiated service for security, fraud, + abuse, or compliance purposes. + THIRD_PARTY_DATA_REQUEST (4): + The principal was compelled to access + customer data in order to respond to a legal + third party data request or process, including + legal processes from customers themselves. + GOOGLE_RESPONSE_TO_PRODUCTION_ALERT (5): + The principal accessed customer data in order + to diagnose or resolve a suspected issue in + services or a known outage. + CLOUD_INITIATED_ACCESS (6): + Similar to 'GOOGLE_INITIATED_SERVICE' or + 'GOOGLE_INITIATED_REVIEW', but with universe agnostic + naming. The principal accessed customer data in order to + diagnose or resolve a suspected issue in services or a known + outage, or for security, fraud, abuse, or compliance review + purposes. + """ + TYPE_UNSPECIFIED = 0 + CUSTOMER_INITIATED_SUPPORT = 1 + GOOGLE_INITIATED_SERVICE = 2 + GOOGLE_INITIATED_REVIEW = 3 + THIRD_PARTY_DATA_REQUEST = 4 + GOOGLE_RESPONSE_TO_PRODUCTION_ALERT = 5 + CLOUD_INITIATED_ACCESS = 6 + + type_: Type = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + detail: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/completion_state.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/completion_state.py new file mode 100644 index 000000000000..9bd9f9d9bf34 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/completion_state.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloudcontrolspartner.v1", + manifest={ + "CompletionState", + }, +) + + +class CompletionState(proto.Enum): + r"""Enum for possible completion states. + + Values: + COMPLETION_STATE_UNSPECIFIED (0): + Unspecified completion state. + PENDING (1): + Task started (has start date) but not yet + completed. + SUCCEEDED (2): + Succeeded state. + FAILED (3): + Failed state. + NOT_APPLICABLE (4): + Not applicable state. + """ + COMPLETION_STATE_UNSPECIFIED = 0 + PENDING = 1 + SUCCEEDED = 2 + FAILED = 3 + NOT_APPLICABLE = 4 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/core.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/core.py new file mode 100644 index 000000000000..0f1ba38796ff --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/core.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloudcontrolspartner.v1", + manifest={ + "OperationMetadata", + }, +) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have been + cancelled successfully have [Operation.error][] value with a + [google.rpc.Status.code][google.rpc.Status.code] of 1, + corresponding to ``Code.CANCELLED``. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/customer_workloads.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/customer_workloads.py new file mode 100644 index 000000000000..7707120df071 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/customer_workloads.py @@ -0,0 +1,300 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloudcontrolspartner_v1.types import ( + completion_state as gcc_completion_state, +) + +__protobuf__ = proto.module( + package="google.cloud.cloudcontrolspartner.v1", + manifest={ + "Workload", + "ListWorkloadsRequest", + "ListWorkloadsResponse", + "GetWorkloadRequest", + "WorkloadOnboardingState", + "WorkloadOnboardingStep", + }, +) + + +class Workload(proto.Message): + r"""Contains metadata around the `Workload + resource `__ + in the Assured Workloads API. + + Attributes: + name (str): + Identifier. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + folder_id (int): + Output only. Folder id this workload is + associated with + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time the resource was created. + folder (str): + Output only. The name of container folder of + the assured workload + workload_onboarding_state (google.cloud.cloudcontrolspartner_v1.types.WorkloadOnboardingState): + Container for workload onboarding steps. + is_onboarded (bool): + Indicates whether a workload is fully + onboarded. + key_management_project_id (str): + The project id of the key management project + for the workload + location (str): + The Google Cloud location of the workload + partner (google.cloud.cloudcontrolspartner_v1.types.Workload.Partner): + Partner associated with this workload. + """ + + class Partner(proto.Enum): + r"""Supported Assured Workloads Partners. + + Values: + PARTNER_UNSPECIFIED (0): + Unknown Partner. + PARTNER_LOCAL_CONTROLS_BY_S3NS (1): + Enum representing S3NS (Thales) partner. + PARTNER_SOVEREIGN_CONTROLS_BY_T_SYSTEMS (2): + Enum representing T_SYSTEM (TSI) partner. + PARTNER_SOVEREIGN_CONTROLS_BY_SIA_MINSAIT (3): + Enum representing SIA_MINSAIT (Indra) partner. + PARTNER_SOVEREIGN_CONTROLS_BY_PSN (4): + Enum representing PSN (TIM) partner. + PARTNER_SOVEREIGN_CONTROLS_BY_CNTXT (6): + Enum representing CNTXT (Kingdom of Saudi + Arabia) partner. + PARTNER_SOVEREIGN_CONTROLS_BY_CNTXT_NO_EKM (7): + Enum representing CNXT (Kingdom of Saudi + Arabia) partner offering without EKM + provisioning. + """ + PARTNER_UNSPECIFIED = 0 + PARTNER_LOCAL_CONTROLS_BY_S3NS = 1 + PARTNER_SOVEREIGN_CONTROLS_BY_T_SYSTEMS = 2 + PARTNER_SOVEREIGN_CONTROLS_BY_SIA_MINSAIT = 3 + PARTNER_SOVEREIGN_CONTROLS_BY_PSN = 4 + PARTNER_SOVEREIGN_CONTROLS_BY_CNTXT = 6 + PARTNER_SOVEREIGN_CONTROLS_BY_CNTXT_NO_EKM = 7 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + folder_id: int = proto.Field( + proto.INT64, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + folder: str = proto.Field( + proto.STRING, + number=4, + ) + workload_onboarding_state: "WorkloadOnboardingState" = proto.Field( + proto.MESSAGE, + number=5, + message="WorkloadOnboardingState", + ) + is_onboarded: bool = proto.Field( + proto.BOOL, + number=6, + ) + key_management_project_id: str = proto.Field( + proto.STRING, + number=7, + ) + location: str = proto.Field( + proto.STRING, + number=8, + ) + partner: Partner = proto.Field( + proto.ENUM, + number=9, + enum=Partner, + ) + + +class ListWorkloadsRequest(proto.Message): + r"""Request to list customer workloads. + + Attributes: + parent (str): + Required. Parent resource Format: + ``organizations/{organization}/locations/{location}/customers/{customer}`` + page_size (int): + The maximum number of workloads to return. + The service may return fewer than this value. If + unspecified, at most 500 workloads will be + returned. + page_token (str): + A page token, received from a previous ``ListWorkloads`` + call. Provide this to retrieve the subsequent page. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + """ + + 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, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListWorkloadsResponse(proto.Message): + r"""Response message for list customer workloads requests. + + Attributes: + workloads (MutableSequence[google.cloud.cloudcontrolspartner_v1.types.Workload]): + List of customer workloads + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + workloads: MutableSequence["Workload"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Workload", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetWorkloadRequest(proto.Message): + r"""Message for getting a customer workload. + + Attributes: + name (str): + Required. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class WorkloadOnboardingState(proto.Message): + r"""Container for workload onboarding steps. + + Attributes: + onboarding_steps (MutableSequence[google.cloud.cloudcontrolspartner_v1.types.WorkloadOnboardingStep]): + List of workload onboarding steps. + """ + + onboarding_steps: MutableSequence["WorkloadOnboardingStep"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="WorkloadOnboardingStep", + ) + + +class WorkloadOnboardingStep(proto.Message): + r"""Container for workload onboarding information. + + Attributes: + step (google.cloud.cloudcontrolspartner_v1.types.WorkloadOnboardingStep.Step): + The onboarding step. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The starting time of the onboarding step. + completion_time (google.protobuf.timestamp_pb2.Timestamp): + The completion time of the onboarding step. + completion_state (google.cloud.cloudcontrolspartner_v1.types.CompletionState): + Output only. The completion state of the + onboarding step. + """ + + class Step(proto.Enum): + r"""Enum for possible onboarding steps. + + Values: + STEP_UNSPECIFIED (0): + Unspecified step. + EKM_PROVISIONED (1): + EKM Provisioned step. + SIGNED_ACCESS_APPROVAL_CONFIGURED (2): + Signed Access Approval step. + """ + STEP_UNSPECIFIED = 0 + EKM_PROVISIONED = 1 + SIGNED_ACCESS_APPROVAL_CONFIGURED = 2 + + step: Step = proto.Field( + proto.ENUM, + number=1, + enum=Step, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + completion_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + completion_state: gcc_completion_state.CompletionState = proto.Field( + proto.ENUM, + number=4, + enum=gcc_completion_state.CompletionState, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/customers.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/customers.py new file mode 100644 index 000000000000..f41ae1f9f7ef --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/customers.py @@ -0,0 +1,233 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloudcontrolspartner_v1.types import ( + completion_state as gcc_completion_state, +) + +__protobuf__ = proto.module( + package="google.cloud.cloudcontrolspartner.v1", + manifest={ + "Customer", + "ListCustomersRequest", + "ListCustomersResponse", + "GetCustomerRequest", + "CustomerOnboardingState", + "CustomerOnboardingStep", + }, +) + + +class Customer(proto.Message): + r"""Contains metadata around a Cloud Controls Partner Customer + + Attributes: + name (str): + Identifier. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}`` + display_name (str): + The customer organization's display name. + E.g. "google.com". + customer_onboarding_state (google.cloud.cloudcontrolspartner_v1.types.CustomerOnboardingState): + Container for customer onboarding steps + is_onboarded (bool): + Indicates whether a customer is fully + onboarded + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + customer_onboarding_state: "CustomerOnboardingState" = proto.Field( + proto.MESSAGE, + number=3, + message="CustomerOnboardingState", + ) + is_onboarded: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListCustomersRequest(proto.Message): + r"""Request to list customers + + Attributes: + parent (str): + Required. Parent resource Format: + ``organizations/{organization}/locations/{location}`` + page_size (int): + The maximum number of Customers to return. + The service may return fewer than this value. If + unspecified, at most 500 Customers will be + returned. + page_token (str): + A page token, received from a previous ``ListCustomers`` + call. Provide this to retrieve the subsequent page. + filter (str): + Optional. Filtering results + order_by (str): + Optional. Hint for how to order the results + """ + + 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, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListCustomersResponse(proto.Message): + r"""Response message for list customer Customers requests + + Attributes: + customers (MutableSequence[google.cloud.cloudcontrolspartner_v1.types.Customer]): + List of customers + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + customers: MutableSequence["Customer"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Customer", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetCustomerRequest(proto.Message): + r"""Message for getting a customer + + Attributes: + name (str): + Required. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CustomerOnboardingState(proto.Message): + r"""Container for customer onboarding steps + + Attributes: + onboarding_steps (MutableSequence[google.cloud.cloudcontrolspartner_v1.types.CustomerOnboardingStep]): + List of customer onboarding steps + """ + + onboarding_steps: MutableSequence["CustomerOnboardingStep"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="CustomerOnboardingStep", + ) + + +class CustomerOnboardingStep(proto.Message): + r"""Container for customer onboarding information + + Attributes: + step (google.cloud.cloudcontrolspartner_v1.types.CustomerOnboardingStep.Step): + The onboarding step + start_time (google.protobuf.timestamp_pb2.Timestamp): + The starting time of the onboarding step + completion_time (google.protobuf.timestamp_pb2.Timestamp): + The completion time of the onboarding step + completion_state (google.cloud.cloudcontrolspartner_v1.types.CompletionState): + Output only. Current state of the step + """ + + class Step(proto.Enum): + r"""Enum for possible onboarding steps + + Values: + STEP_UNSPECIFIED (0): + Unspecified step + KAJ_ENROLLMENT (1): + KAJ Enrollment + CUSTOMER_ENVIRONMENT (2): + Customer Environment + """ + STEP_UNSPECIFIED = 0 + KAJ_ENROLLMENT = 1 + CUSTOMER_ENVIRONMENT = 2 + + step: Step = proto.Field( + proto.ENUM, + number=1, + enum=Step, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + completion_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + completion_state: gcc_completion_state.CompletionState = proto.Field( + proto.ENUM, + number=4, + enum=gcc_completion_state.CompletionState, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/ekm_connections.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/ekm_connections.py new file mode 100644 index 000000000000..7a4f86791fb8 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/ekm_connections.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloudcontrolspartner.v1", + manifest={ + "EkmConnections", + "GetEkmConnectionsRequest", + "EkmConnection", + }, +) + + +class EkmConnections(proto.Message): + r"""The EKM connections associated with a workload + + Attributes: + name (str): + Identifier. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/ekmConnections`` + ekm_connections (MutableSequence[google.cloud.cloudcontrolspartner_v1.types.EkmConnection]): + The EKM connections associated with the + workload + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ekm_connections: MutableSequence["EkmConnection"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="EkmConnection", + ) + + +class GetEkmConnectionsRequest(proto.Message): + r"""Request for getting the EKM connections associated with a + workload + + Attributes: + name (str): + Required. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/ekmConnections`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EkmConnection(proto.Message): + r"""Details about the EKM connection + + Attributes: + connection_name (str): + Resource name of the EKM connection in the format: + projects/{project}/locations/{location}/ekmConnections/{ekm_connection} + connection_state (google.cloud.cloudcontrolspartner_v1.types.EkmConnection.ConnectionState): + Output only. The connection state + connection_error (google.cloud.cloudcontrolspartner_v1.types.EkmConnection.ConnectionError): + The connection error that occurred if any + """ + + class ConnectionState(proto.Enum): + r"""The EKM connection state. + + Values: + CONNECTION_STATE_UNSPECIFIED (0): + Unspecified EKM connection state + AVAILABLE (1): + Available EKM connection state + NOT_AVAILABLE (2): + Not available EKM connection state + ERROR (3): + Error EKM connection state + PERMISSION_DENIED (4): + Permission denied EKM connection state + """ + CONNECTION_STATE_UNSPECIFIED = 0 + AVAILABLE = 1 + NOT_AVAILABLE = 2 + ERROR = 3 + PERMISSION_DENIED = 4 + + class ConnectionError(proto.Message): + r"""Information around the error that occurred if the connection + state is anything other than available or unspecified + + Attributes: + error_domain (str): + The error domain for the error + error_message (str): + The error message for the error + """ + + error_domain: str = proto.Field( + proto.STRING, + number=1, + ) + error_message: str = proto.Field( + proto.STRING, + number=2, + ) + + connection_name: str = proto.Field( + proto.STRING, + number=1, + ) + connection_state: ConnectionState = proto.Field( + proto.ENUM, + number=2, + enum=ConnectionState, + ) + connection_error: ConnectionError = proto.Field( + proto.MESSAGE, + number=3, + message=ConnectionError, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/monitoring.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/monitoring.py new file mode 100644 index 000000000000..aaf5dd61255b --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/monitoring.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.cloudcontrolspartner.v1", + manifest={}, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/partner_permissions.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/partner_permissions.py new file mode 100644 index 000000000000..652e9932cf81 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/partner_permissions.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloudcontrolspartner.v1", + manifest={ + "PartnerPermissions", + "GetPartnerPermissionsRequest", + }, +) + + +class PartnerPermissions(proto.Message): + r"""The permissions granted to the partner for a workload + + Attributes: + name (str): + Identifier. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/partnerPermissions`` + partner_permissions (MutableSequence[google.cloud.cloudcontrolspartner_v1.types.PartnerPermissions.Permission]): + The partner permissions granted for the + workload + """ + + class Permission(proto.Enum): + r""" + + Values: + PERMISSION_UNSPECIFIED (0): + Unspecified partner permission + ACCESS_TRANSPARENCY_AND_EMERGENCY_ACCESS_LOGS (1): + Permission for Access Transparency and + emergency logs + ASSURED_WORKLOADS_MONITORING (2): + Permission for Assured Workloads monitoring + violations + ACCESS_APPROVAL_REQUESTS (3): + Permission for Access Approval requests + ASSURED_WORKLOADS_EKM_CONNECTION_STATUS (4): + Permission for External Key Manager + connection status + """ + PERMISSION_UNSPECIFIED = 0 + ACCESS_TRANSPARENCY_AND_EMERGENCY_ACCESS_LOGS = 1 + ASSURED_WORKLOADS_MONITORING = 2 + ACCESS_APPROVAL_REQUESTS = 3 + ASSURED_WORKLOADS_EKM_CONNECTION_STATUS = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + partner_permissions: MutableSequence[Permission] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=Permission, + ) + + +class GetPartnerPermissionsRequest(proto.Message): + r"""Request for getting the partner permissions granted for a + workload + + Attributes: + name (str): + Required. Name of the resource to get in the format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/partnerPermissions`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/partners.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/partners.py new file mode 100644 index 000000000000..5a5d8894972f --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/partners.py @@ -0,0 +1,188 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloudcontrolspartner.v1", + manifest={ + "Partner", + "GetPartnerRequest", + "Sku", + "EkmMetadata", + }, +) + + +class Partner(proto.Message): + r"""Message describing Partner resource + + Attributes: + name (str): + Identifier. The resource name of the partner. Format: + ``organizations/{organization}/locations/{location}/partner`` + Example: + "organizations/123456/locations/us-central1/partner". + skus (MutableSequence[google.cloud.cloudcontrolspartner_v1.types.Sku]): + List of SKUs the partner is offering + ekm_solutions (MutableSequence[google.cloud.cloudcontrolspartner_v1.types.EkmMetadata]): + List of Google Cloud supported EKM partners + supported by the partner + operated_cloud_regions (MutableSequence[str]): + List of Google Cloud regions that the partner + sells services to customers. Valid Google Cloud + regions found here: + + https://cloud.google.com/compute/docs/regions-zones + partner_project_id (str): + Google Cloud project ID in the partner's + Google Cloud organization for receiving enhanced + Logs for Partners. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time the resource was created + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last time the resource was + updated + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + skus: MutableSequence["Sku"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="Sku", + ) + ekm_solutions: MutableSequence["EkmMetadata"] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="EkmMetadata", + ) + operated_cloud_regions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + partner_project_id: str = proto.Field( + proto.STRING, + number=7, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +class GetPartnerRequest(proto.Message): + r"""Message for getting a Partner + + Attributes: + name (str): + Required. Format: + ``organizations/{organization}/locations/{location}/partner`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class Sku(proto.Message): + r"""Represents the SKU a partner owns inside Google Cloud to sell + to customers. + + Attributes: + id (str): + Argentum product SKU, that is associated with + the partner offerings to customers used by + Syntro for billing purposes. SKUs can represent + resold Google products or support services. + display_name (str): + Display name of the product identified by the + SKU. A partner may want to show partner branded + names for their offerings such as local + sovereign cloud solutions. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +class EkmMetadata(proto.Message): + r"""Holds information needed by Mudbray to use partner EKMs for + workloads. + + Attributes: + ekm_solution (google.cloud.cloudcontrolspartner_v1.types.EkmMetadata.EkmSolution): + The Cloud EKM partner. + ekm_endpoint_uri (str): + Endpoint for sending requests to the EKM for + key provisioning during Assured Workload + creation. + """ + + class EkmSolution(proto.Enum): + r"""Represents Google Cloud supported external key management partners + `Google Cloud EKM partners + docs `__. + + Values: + EKM_SOLUTION_UNSPECIFIED (0): + Unspecified EKM solution + FORTANIX (1): + EKM Partner Fortanix + FUTUREX (2): + EKM Partner FutureX + THALES (3): + EKM Partner Thales + VIRTRU (4): + EKM Partner Virtu + """ + EKM_SOLUTION_UNSPECIFIED = 0 + FORTANIX = 1 + FUTUREX = 2 + THALES = 3 + VIRTRU = 4 + + ekm_solution: EkmSolution = proto.Field( + proto.ENUM, + number=1, + enum=EkmSolution, + ) + ekm_endpoint_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/violations.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/violations.py new file mode 100644 index 000000000000..3f27d9c9b665 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1/types/violations.py @@ -0,0 +1,388 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 +from google.type import interval_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.cloudcontrolspartner.v1", + manifest={ + "Violation", + "ListViolationsRequest", + "ListViolationsResponse", + "GetViolationRequest", + }, +) + + +class Violation(proto.Message): + r"""Details of resource Violation + + Attributes: + name (str): + Identifier. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/violations/{violation}`` + description (str): + Output only. Description for the Violation. + e.g. OrgPolicy gcp.resourceLocations has non + compliant value. + begin_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time of the event which + triggered the Violation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last time when the Violation + record was updated. + resolve_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time of the event which fixed + the Violation. If the violation is ACTIVE this + will be empty. + category (str): + Output only. Category under which this + violation is mapped. e.g. Location, Service + Usage, Access, Encryption, etc. + state (google.cloud.cloudcontrolspartner_v1.types.Violation.State): + Output only. State of the violation + non_compliant_org_policy (str): + Output only. Immutable. Name of the OrgPolicy which was + modified with non-compliant change and resulted this + violation. Format: + ``projects/{project_number}/policies/{constraint_name}`` + ``folders/{folder_id}/policies/{constraint_name}`` + ``organizations/{organization_id}/policies/{constraint_name}`` + folder_id (int): + The folder_id of the violation + remediation (google.cloud.cloudcontrolspartner_v1.types.Violation.Remediation): + Output only. Compliance violation remediation + """ + + class State(proto.Enum): + r"""Violation State Values + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + RESOLVED (1): + Violation is resolved. + UNRESOLVED (2): + Violation is Unresolved + EXCEPTION (3): + Violation is Exception + """ + STATE_UNSPECIFIED = 0 + RESOLVED = 1 + UNRESOLVED = 2 + EXCEPTION = 3 + + class Remediation(proto.Message): + r"""Represents remediation guidance to resolve compliance + violation for AssuredWorkload + + Attributes: + instructions (google.cloud.cloudcontrolspartner_v1.types.Violation.Remediation.Instructions): + Required. Remediation instructions to resolve + violations + compliant_values (MutableSequence[str]): + Values that can resolve the violation + For example: for list org policy violations, + this will either be the list of allowed or + denied values + remediation_type (google.cloud.cloudcontrolspartner_v1.types.Violation.Remediation.RemediationType): + Output only. Remediation type based on the + type of org policy values violated + """ + + class RemediationType(proto.Enum): + r"""Classifying remediation into various types based on the kind + of violation. For example, violations caused due to changes in + boolean org policy requires different remediation instructions + compared to violation caused due to changes in allowed values of + list org policy. + + Values: + REMEDIATION_TYPE_UNSPECIFIED (0): + Unspecified remediation type + REMEDIATION_BOOLEAN_ORG_POLICY_VIOLATION (1): + Remediation type for boolean org policy + REMEDIATION_LIST_ALLOWED_VALUES_ORG_POLICY_VIOLATION (2): + Remediation type for list org policy which + have allowed values in the monitoring rule + REMEDIATION_LIST_DENIED_VALUES_ORG_POLICY_VIOLATION (3): + Remediation type for list org policy which + have denied values in the monitoring rule + REMEDIATION_RESTRICT_CMEK_CRYPTO_KEY_PROJECTS_ORG_POLICY_VIOLATION (4): + Remediation type for + gcp.restrictCmekCryptoKeyProjects + REMEDIATION_RESOURCE_VIOLATION (5): + Remediation type for resource violation. + """ + REMEDIATION_TYPE_UNSPECIFIED = 0 + REMEDIATION_BOOLEAN_ORG_POLICY_VIOLATION = 1 + REMEDIATION_LIST_ALLOWED_VALUES_ORG_POLICY_VIOLATION = 2 + REMEDIATION_LIST_DENIED_VALUES_ORG_POLICY_VIOLATION = 3 + REMEDIATION_RESTRICT_CMEK_CRYPTO_KEY_PROJECTS_ORG_POLICY_VIOLATION = 4 + REMEDIATION_RESOURCE_VIOLATION = 5 + + class Instructions(proto.Message): + r"""Instructions to remediate violation + + Attributes: + gcloud_instructions (google.cloud.cloudcontrolspartner_v1.types.Violation.Remediation.Instructions.Gcloud): + Remediation instructions to resolve violation + via gcloud cli + console_instructions (google.cloud.cloudcontrolspartner_v1.types.Violation.Remediation.Instructions.Console): + Remediation instructions to resolve violation + via cloud console + """ + + class Gcloud(proto.Message): + r"""Remediation instructions to resolve violation via gcloud cli + + Attributes: + gcloud_commands (MutableSequence[str]): + Gcloud command to resolve violation + steps (MutableSequence[str]): + Steps to resolve violation via gcloud cli + additional_links (MutableSequence[str]): + Additional urls for more information about + steps + """ + + gcloud_commands: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + steps: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + additional_links: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + class Console(proto.Message): + r"""Remediation instructions to resolve violation via cloud + console + + Attributes: + console_uris (MutableSequence[str]): + Link to console page where violations can be + resolved + steps (MutableSequence[str]): + Steps to resolve violation via cloud console + additional_links (MutableSequence[str]): + Additional urls for more information about + steps + """ + + console_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + steps: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + additional_links: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + gcloud_instructions: "Violation.Remediation.Instructions.Gcloud" = ( + proto.Field( + proto.MESSAGE, + number=1, + message="Violation.Remediation.Instructions.Gcloud", + ) + ) + console_instructions: "Violation.Remediation.Instructions.Console" = ( + proto.Field( + proto.MESSAGE, + number=2, + message="Violation.Remediation.Instructions.Console", + ) + ) + + instructions: "Violation.Remediation.Instructions" = proto.Field( + proto.MESSAGE, + number=1, + message="Violation.Remediation.Instructions", + ) + compliant_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + remediation_type: "Violation.Remediation.RemediationType" = proto.Field( + proto.ENUM, + number=3, + enum="Violation.Remediation.RemediationType", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + begin_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + resolve_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + category: str = proto.Field( + proto.STRING, + number=6, + ) + state: State = proto.Field( + proto.ENUM, + number=7, + enum=State, + ) + non_compliant_org_policy: str = proto.Field( + proto.STRING, + number=8, + ) + folder_id: int = proto.Field( + proto.INT64, + number=9, + ) + remediation: Remediation = proto.Field( + proto.MESSAGE, + number=13, + message=Remediation, + ) + + +class ListViolationsRequest(proto.Message): + r"""Message for requesting list of Violations + + Attributes: + parent (str): + Required. Parent resource Format + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + page_size (int): + Optional. The maximum number of customers row + to return. The service may return fewer than + this value. If unspecified, at most 10 customers + will be returned. + page_token (str): + Optional. A page token, received from a previous + ``ListViolations`` call. Provide this to retrieve the + subsequent page. + filter (str): + Optional. Filtering results + order_by (str): + Optional. Hint for how to order the results + interval (google.type.interval_pb2.Interval): + Optional. Specifies the interval for + retrieving violations. if unspecified, all + violations will be returned. + """ + + 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, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + interval: interval_pb2.Interval = proto.Field( + proto.MESSAGE, + number=6, + message=interval_pb2.Interval, + ) + + +class ListViolationsResponse(proto.Message): + r"""Response message for list customer violation requests + + Attributes: + violations (MutableSequence[google.cloud.cloudcontrolspartner_v1.types.Violation]): + List of violation + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Workloads that could not be reached due to + permission errors or any other error. Ref: + https://google.aip.dev/217 + """ + + @property + def raw_page(self): + return self + + violations: MutableSequence["Violation"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Violation", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetViolationRequest(proto.Message): + r"""Message for getting a Violation + + Attributes: + name (str): + Required. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/violations/{violation}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/__init__.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/__init__.py new file mode 100644 index 000000000000..cdbd10879791 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/__init__.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 google.cloud.cloudcontrolspartner_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.cloud_controls_partner_core import ( + CloudControlsPartnerCoreAsyncClient, + CloudControlsPartnerCoreClient, +) +from .services.cloud_controls_partner_monitoring import ( + CloudControlsPartnerMonitoringAsyncClient, + CloudControlsPartnerMonitoringClient, +) +from .types.access_approval_requests import ( + AccessApprovalRequest, + AccessReason, + ListAccessApprovalRequestsRequest, + ListAccessApprovalRequestsResponse, +) +from .types.completion_state import CompletionState +from .types.core import OperationMetadata +from .types.customer_workloads import ( + GetWorkloadRequest, + ListWorkloadsRequest, + ListWorkloadsResponse, + Workload, + WorkloadOnboardingState, + WorkloadOnboardingStep, +) +from .types.customers import ( + Customer, + CustomerOnboardingState, + CustomerOnboardingStep, + GetCustomerRequest, + ListCustomersRequest, + ListCustomersResponse, +) +from .types.ekm_connections import ( + EkmConnection, + EkmConnections, + GetEkmConnectionsRequest, +) +from .types.partner_permissions import GetPartnerPermissionsRequest, PartnerPermissions +from .types.partners import EkmMetadata, GetPartnerRequest, Partner, Sku +from .types.violations import ( + GetViolationRequest, + ListViolationsRequest, + ListViolationsResponse, + Violation, +) + +__all__ = ( + "CloudControlsPartnerCoreAsyncClient", + "CloudControlsPartnerMonitoringAsyncClient", + "AccessApprovalRequest", + "AccessReason", + "CloudControlsPartnerCoreClient", + "CloudControlsPartnerMonitoringClient", + "CompletionState", + "Customer", + "CustomerOnboardingState", + "CustomerOnboardingStep", + "EkmConnection", + "EkmConnections", + "EkmMetadata", + "GetCustomerRequest", + "GetEkmConnectionsRequest", + "GetPartnerPermissionsRequest", + "GetPartnerRequest", + "GetViolationRequest", + "GetWorkloadRequest", + "ListAccessApprovalRequestsRequest", + "ListAccessApprovalRequestsResponse", + "ListCustomersRequest", + "ListCustomersResponse", + "ListViolationsRequest", + "ListViolationsResponse", + "ListWorkloadsRequest", + "ListWorkloadsResponse", + "OperationMetadata", + "Partner", + "PartnerPermissions", + "Sku", + "Violation", + "Workload", + "WorkloadOnboardingState", + "WorkloadOnboardingStep", +) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/gapic_metadata.json b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..5e2cd4e90ca7 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/gapic_metadata.json @@ -0,0 +1,197 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.cloudcontrolspartner_v1beta", + "protoPackage": "google.cloud.cloudcontrolspartner.v1beta", + "schema": "1.0", + "services": { + "CloudControlsPartnerCore": { + "clients": { + "grpc": { + "libraryClient": "CloudControlsPartnerCoreClient", + "rpcs": { + "GetCustomer": { + "methods": [ + "get_customer" + ] + }, + "GetEkmConnections": { + "methods": [ + "get_ekm_connections" + ] + }, + "GetPartner": { + "methods": [ + "get_partner" + ] + }, + "GetPartnerPermissions": { + "methods": [ + "get_partner_permissions" + ] + }, + "GetWorkload": { + "methods": [ + "get_workload" + ] + }, + "ListAccessApprovalRequests": { + "methods": [ + "list_access_approval_requests" + ] + }, + "ListCustomers": { + "methods": [ + "list_customers" + ] + }, + "ListWorkloads": { + "methods": [ + "list_workloads" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CloudControlsPartnerCoreAsyncClient", + "rpcs": { + "GetCustomer": { + "methods": [ + "get_customer" + ] + }, + "GetEkmConnections": { + "methods": [ + "get_ekm_connections" + ] + }, + "GetPartner": { + "methods": [ + "get_partner" + ] + }, + "GetPartnerPermissions": { + "methods": [ + "get_partner_permissions" + ] + }, + "GetWorkload": { + "methods": [ + "get_workload" + ] + }, + "ListAccessApprovalRequests": { + "methods": [ + "list_access_approval_requests" + ] + }, + "ListCustomers": { + "methods": [ + "list_customers" + ] + }, + "ListWorkloads": { + "methods": [ + "list_workloads" + ] + } + } + }, + "rest": { + "libraryClient": "CloudControlsPartnerCoreClient", + "rpcs": { + "GetCustomer": { + "methods": [ + "get_customer" + ] + }, + "GetEkmConnections": { + "methods": [ + "get_ekm_connections" + ] + }, + "GetPartner": { + "methods": [ + "get_partner" + ] + }, + "GetPartnerPermissions": { + "methods": [ + "get_partner_permissions" + ] + }, + "GetWorkload": { + "methods": [ + "get_workload" + ] + }, + "ListAccessApprovalRequests": { + "methods": [ + "list_access_approval_requests" + ] + }, + "ListCustomers": { + "methods": [ + "list_customers" + ] + }, + "ListWorkloads": { + "methods": [ + "list_workloads" + ] + } + } + } + } + }, + "CloudControlsPartnerMonitoring": { + "clients": { + "grpc": { + "libraryClient": "CloudControlsPartnerMonitoringClient", + "rpcs": { + "GetViolation": { + "methods": [ + "get_violation" + ] + }, + "ListViolations": { + "methods": [ + "list_violations" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CloudControlsPartnerMonitoringAsyncClient", + "rpcs": { + "GetViolation": { + "methods": [ + "get_violation" + ] + }, + "ListViolations": { + "methods": [ + "list_violations" + ] + } + } + }, + "rest": { + "libraryClient": "CloudControlsPartnerMonitoringClient", + "rpcs": { + "GetViolation": { + "methods": [ + "get_violation" + ] + }, + "ListViolations": { + "methods": [ + "list_violations" + ] + } + } + } + } + } + } +} 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 new file mode 100644 index 000000000000..a7d39deb7a45 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/py.typed b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/py.typed new file mode 100644 index 000000000000..ff1c04426ba7 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-cloudcontrolspartner package uses inline types. diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/__init__.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/__init__.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/__init__.py new file mode 100644 index 000000000000..46206aebecfd --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .async_client import CloudControlsPartnerCoreAsyncClient +from .client import CloudControlsPartnerCoreClient + +__all__ = ( + "CloudControlsPartnerCoreClient", + "CloudControlsPartnerCoreAsyncClient", +) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/async_client.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/async_client.py new file mode 100644 index 000000000000..f96c05567377 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/async_client.py @@ -0,0 +1,1262 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.cloudcontrolspartner_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core import ( + pagers, +) +from google.cloud.cloudcontrolspartner_v1beta.types import ( + access_approval_requests, + customer_workloads, + customers, + ekm_connections, + partner_permissions, + partners, +) + +from .client import CloudControlsPartnerCoreClient +from .transports.base import DEFAULT_CLIENT_INFO, CloudControlsPartnerCoreTransport +from .transports.grpc_asyncio import CloudControlsPartnerCoreGrpcAsyncIOTransport + + +class CloudControlsPartnerCoreAsyncClient: + """Service describing handlers for resources""" + + _client: CloudControlsPartnerCoreClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = CloudControlsPartnerCoreClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CloudControlsPartnerCoreClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ( + CloudControlsPartnerCoreClient._DEFAULT_ENDPOINT_TEMPLATE + ) + _DEFAULT_UNIVERSE = CloudControlsPartnerCoreClient._DEFAULT_UNIVERSE + + access_approval_request_path = staticmethod( + CloudControlsPartnerCoreClient.access_approval_request_path + ) + parse_access_approval_request_path = staticmethod( + CloudControlsPartnerCoreClient.parse_access_approval_request_path + ) + customer_path = staticmethod(CloudControlsPartnerCoreClient.customer_path) + parse_customer_path = staticmethod( + CloudControlsPartnerCoreClient.parse_customer_path + ) + ekm_connections_path = staticmethod( + CloudControlsPartnerCoreClient.ekm_connections_path + ) + parse_ekm_connections_path = staticmethod( + CloudControlsPartnerCoreClient.parse_ekm_connections_path + ) + partner_path = staticmethod(CloudControlsPartnerCoreClient.partner_path) + parse_partner_path = staticmethod(CloudControlsPartnerCoreClient.parse_partner_path) + partner_permissions_path = staticmethod( + CloudControlsPartnerCoreClient.partner_permissions_path + ) + parse_partner_permissions_path = staticmethod( + CloudControlsPartnerCoreClient.parse_partner_permissions_path + ) + workload_path = staticmethod(CloudControlsPartnerCoreClient.workload_path) + parse_workload_path = staticmethod( + CloudControlsPartnerCoreClient.parse_workload_path + ) + common_billing_account_path = staticmethod( + CloudControlsPartnerCoreClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + CloudControlsPartnerCoreClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(CloudControlsPartnerCoreClient.common_folder_path) + parse_common_folder_path = staticmethod( + CloudControlsPartnerCoreClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + CloudControlsPartnerCoreClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + CloudControlsPartnerCoreClient.parse_common_organization_path + ) + common_project_path = staticmethod( + CloudControlsPartnerCoreClient.common_project_path + ) + parse_common_project_path = staticmethod( + CloudControlsPartnerCoreClient.parse_common_project_path + ) + common_location_path = staticmethod( + CloudControlsPartnerCoreClient.common_location_path + ) + parse_common_location_path = staticmethod( + CloudControlsPartnerCoreClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudControlsPartnerCoreAsyncClient: The constructed client. + """ + return CloudControlsPartnerCoreClient.from_service_account_info.__func__(CloudControlsPartnerCoreAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudControlsPartnerCoreAsyncClient: The constructed client. + """ + return CloudControlsPartnerCoreClient.from_service_account_file.__func__(CloudControlsPartnerCoreAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CloudControlsPartnerCoreClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CloudControlsPartnerCoreTransport: + """Returns the transport used by the client instance. + + Returns: + CloudControlsPartnerCoreTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial( + type(CloudControlsPartnerCoreClient).get_transport_class, + type(CloudControlsPartnerCoreClient), + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CloudControlsPartnerCoreTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud controls partner core async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CloudControlsPartnerCoreTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CloudControlsPartnerCoreClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def get_workload( + self, + request: Optional[Union[customer_workloads.GetWorkloadRequest, 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]] = (), + ) -> customer_workloads.Workload: + r"""Gets details of a single workload + + .. 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 cloudcontrolspartner_v1beta + + async def sample_get_workload(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetWorkloadRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workload(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1beta.types.GetWorkloadRequest, dict]]): + The request object. Message for getting a customer + workload. + name (:class:`str`): + Required. Format: + + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload} + + 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.cloudcontrolspartner_v1beta.types.Workload: + Contains metadata around the [Workload + resource](\ https://cloud.google.com/assured-workloads/docs/reference/rest/Shared.Types/Workload) + in the Assured Workloads API. + + """ + # 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." + ) + + request = customer_workloads.GetWorkloadRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_workload, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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_workloads( + self, + request: Optional[Union[customer_workloads.ListWorkloadsRequest, 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.ListWorkloadsAsyncPager: + r"""Lists customer workloads for a given customer org id + + .. 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 cloudcontrolspartner_v1beta + + async def sample_list_workloads(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.ListWorkloadsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workloads(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1beta.types.ListWorkloadsRequest, dict]]): + The request object. Request to list customer workloads. + parent (:class:`str`): + Required. Parent resource + Format: + + organizations/{organization}/locations/{location}/customers/{customer} + + 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.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.pagers.ListWorkloadsAsyncPager: + Response message for list customer + workloads requests. + 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." + ) + + request = customer_workloads.ListWorkloadsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_workloads, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListWorkloadsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_customer( + self, + request: Optional[Union[customers.GetCustomerRequest, 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]] = (), + ) -> customers.Customer: + r"""Gets details of a single customer + + .. 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 cloudcontrolspartner_v1beta + + async def sample_get_customer(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetCustomerRequest( + name="name_value", + ) + + # Make the request + response = await client.get_customer(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1beta.types.GetCustomerRequest, dict]]): + The request object. Message for getting a customer + name (:class:`str`): + Required. Format: + + organizations/{organization}/locations/{location}/customers/{customer} + + 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.cloudcontrolspartner_v1beta.types.Customer: + Contains metadata around a Cloud + Controls Partner Customer + + """ + # 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." + ) + + request = customers.GetCustomerRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_customer, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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_customers( + self, + request: Optional[Union[customers.ListCustomersRequest, 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.ListCustomersAsyncPager: + r"""Lists customers of a partner identified by its Google + Cloud organization ID + + .. 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 cloudcontrolspartner_v1beta + + async def sample_list_customers(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.ListCustomersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_customers(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1beta.types.ListCustomersRequest, dict]]): + The request object. Request to list customers + parent (:class:`str`): + Required. Parent resource + Format: + organizations/{organization}/locations/{location} + + 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.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.pagers.ListCustomersAsyncPager: + Response message for list customer + Customers requests + 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." + ) + + request = customers.ListCustomersRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_customers, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListCustomersAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_ekm_connections( + self, + request: Optional[Union[ekm_connections.GetEkmConnectionsRequest, 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]] = (), + ) -> ekm_connections.EkmConnections: + r"""Gets the EKM connections associated with a workload + + .. 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 cloudcontrolspartner_v1beta + + async def sample_get_ekm_connections(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetEkmConnectionsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_ekm_connections(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1beta.types.GetEkmConnectionsRequest, dict]]): + The request object. Request for getting the EKM + connections associated with a workload + name (:class:`str`): + Required. Format: + + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/ekmConnections + + 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.cloudcontrolspartner_v1beta.types.EkmConnections: + The EKM connections associated with a + workload + + """ + # 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." + ) + + request = ekm_connections.GetEkmConnectionsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_ekm_connections, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 get_partner_permissions( + self, + request: Optional[ + Union[partner_permissions.GetPartnerPermissionsRequest, 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]] = (), + ) -> partner_permissions.PartnerPermissions: + r"""Gets the partner permissions granted for a workload + + .. 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 cloudcontrolspartner_v1beta + + async def sample_get_partner_permissions(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetPartnerPermissionsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_partner_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1beta.types.GetPartnerPermissionsRequest, dict]]): + The request object. Request for getting the partner + permissions granted for a workload + name (:class:`str`): + Required. Name of the resource to get + in the format: + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/partnerPermissions + + 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.cloudcontrolspartner_v1beta.types.PartnerPermissions: + The permissions granted to the + partner for a workload + + """ + # 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." + ) + + request = partner_permissions.GetPartnerPermissionsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_partner_permissions, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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_access_approval_requests( + self, + request: Optional[ + Union[access_approval_requests.ListAccessApprovalRequestsRequest, 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.ListAccessApprovalRequestsAsyncPager: + r"""Lists access requests associated with a workload + + .. 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 cloudcontrolspartner_v1beta + + async def sample_list_access_approval_requests(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.ListAccessApprovalRequestsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_access_approval_requests(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1beta.types.ListAccessApprovalRequestsRequest, dict]]): + The request object. Request for getting the access + requests associated with a workload. + parent (:class:`str`): + Required. Parent resource + Format: + + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload} + + 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.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.pagers.ListAccessApprovalRequestsAsyncPager: + Response message for list access + requests. + 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." + ) + + request = access_approval_requests.ListAccessApprovalRequestsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_access_approval_requests, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListAccessApprovalRequestsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_partner( + self, + request: Optional[Union[partners.GetPartnerRequest, 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]] = (), + ) -> partners.Partner: + r"""Get details of a Partner. + + .. 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 cloudcontrolspartner_v1beta + + async def sample_get_partner(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetPartnerRequest( + name="name_value", + ) + + # Make the request + response = await client.get_partner(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1beta.types.GetPartnerRequest, dict]]): + The request object. Message for getting a Partner + name (:class:`str`): + Required. Format: + organizations/{organization}/locations/{location}/partner + + 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.cloudcontrolspartner_v1beta.types.Partner: + Message describing Partner 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." + ) + + request = partners.GetPartnerRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_partner, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 __aenter__(self) -> "CloudControlsPartnerCoreAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("CloudControlsPartnerCoreAsyncClient",) 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 new file mode 100644 index 000000000000..2c8771c89c01 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/client.py @@ -0,0 +1,1714 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.cloudcontrolspartner_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core import ( + pagers, +) +from google.cloud.cloudcontrolspartner_v1beta.types import ( + access_approval_requests, + customer_workloads, + customers, + ekm_connections, + partner_permissions, + partners, +) + +from .transports.base import DEFAULT_CLIENT_INFO, CloudControlsPartnerCoreTransport +from .transports.grpc import CloudControlsPartnerCoreGrpcTransport +from .transports.grpc_asyncio import CloudControlsPartnerCoreGrpcAsyncIOTransport +from .transports.rest import CloudControlsPartnerCoreRestTransport + + +class CloudControlsPartnerCoreClientMeta(type): + """Metaclass for the CloudControlsPartnerCore client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[CloudControlsPartnerCoreTransport]] + _transport_registry["grpc"] = CloudControlsPartnerCoreGrpcTransport + _transport_registry["grpc_asyncio"] = CloudControlsPartnerCoreGrpcAsyncIOTransport + _transport_registry["rest"] = CloudControlsPartnerCoreRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[CloudControlsPartnerCoreTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CloudControlsPartnerCoreClient(metaclass=CloudControlsPartnerCoreClientMeta): + """Service describing handlers for resources""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "cloudcontrolspartner.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "cloudcontrolspartner.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudControlsPartnerCoreClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudControlsPartnerCoreClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CloudControlsPartnerCoreTransport: + """Returns the transport used by the client instance. + + Returns: + CloudControlsPartnerCoreTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def access_approval_request_path( + organization: str, + location: str, + customer: str, + workload: str, + access_approval_request: str, + ) -> str: + """Returns a fully-qualified access_approval_request string.""" + return "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/accessApprovalRequests/{access_approval_request}".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + access_approval_request=access_approval_request, + ) + + @staticmethod + def parse_access_approval_request_path(path: str) -> Dict[str, str]: + """Parses a access_approval_request path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/customers/(?P.+?)/workloads/(?P.+?)/accessApprovalRequests/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def customer_path( + organization: str, + location: str, + customer: str, + ) -> str: + """Returns a fully-qualified customer string.""" + return "organizations/{organization}/locations/{location}/customers/{customer}".format( + organization=organization, + location=location, + customer=customer, + ) + + @staticmethod + def parse_customer_path(path: str) -> Dict[str, str]: + """Parses a customer path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/customers/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def ekm_connections_path( + organization: str, + location: str, + customer: str, + workload: str, + ) -> str: + """Returns a fully-qualified ekm_connections string.""" + return "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/ekmConnections".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + ) + + @staticmethod + def parse_ekm_connections_path(path: str) -> Dict[str, str]: + """Parses a ekm_connections path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/customers/(?P.+?)/workloads/(?P.+?)/ekmConnections$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def partner_path( + organization: str, + location: str, + ) -> str: + """Returns a fully-qualified partner string.""" + return "organizations/{organization}/locations/{location}/partner".format( + organization=organization, + location=location, + ) + + @staticmethod + def parse_partner_path(path: str) -> Dict[str, str]: + """Parses a partner path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/partner$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def partner_permissions_path( + organization: str, + location: str, + customer: str, + workload: str, + ) -> str: + """Returns a fully-qualified partner_permissions string.""" + return "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/partnerPermissions".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + ) + + @staticmethod + def parse_partner_permissions_path(path: str) -> Dict[str, str]: + """Parses a partner_permissions path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/customers/(?P.+?)/workloads/(?P.+?)/partnerPermissions$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def workload_path( + organization: str, + location: str, + customer: str, + workload: str, + ) -> str: + """Returns a fully-qualified workload string.""" + return "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + ) + + @staticmethod + def parse_workload_path(path: str) -> Dict[str, str]: + """Parses a workload path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/customers/(?P.+?)/workloads/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = CloudControlsPartnerCoreClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = CloudControlsPartnerCoreClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + CloudControlsPartnerCoreClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = CloudControlsPartnerCoreClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + 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. + + Returns: + bool: True iff the configured universe domain is valid. + + 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 + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, CloudControlsPartnerCoreTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud controls partner core client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CloudControlsPartnerCoreTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = CloudControlsPartnerCoreClient._read_environment_variables() + self._client_cert_source = ( + CloudControlsPartnerCoreClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = CloudControlsPartnerCoreClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, CloudControlsPartnerCoreTransport) + if transport_provided: + # transport is a CloudControlsPartnerCoreTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(CloudControlsPartnerCoreTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or CloudControlsPartnerCoreClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + Transport = type(self).get_transport_class(cast(str, transport)) + self._transport = Transport( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def get_workload( + self, + request: Optional[Union[customer_workloads.GetWorkloadRequest, 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]] = (), + ) -> customer_workloads.Workload: + r"""Gets details of a single workload + + .. 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 cloudcontrolspartner_v1beta + + def sample_get_workload(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetWorkloadRequest( + name="name_value", + ) + + # Make the request + response = client.get_workload(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1beta.types.GetWorkloadRequest, dict]): + The request object. Message for getting a customer + workload. + name (str): + Required. Format: + + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload} + + 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.cloudcontrolspartner_v1beta.types.Workload: + Contains metadata around the [Workload + resource](\ https://cloud.google.com/assured-workloads/docs/reference/rest/Shared.Types/Workload) + in the Assured Workloads API. + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a customer_workloads.GetWorkloadRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, customer_workloads.GetWorkloadRequest): + request = customer_workloads.GetWorkloadRequest(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_workload] + + # 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_workloads( + self, + request: Optional[Union[customer_workloads.ListWorkloadsRequest, 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.ListWorkloadsPager: + r"""Lists customer workloads for a given customer org id + + .. 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 cloudcontrolspartner_v1beta + + def sample_list_workloads(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.ListWorkloadsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workloads(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1beta.types.ListWorkloadsRequest, dict]): + The request object. Request to list customer workloads. + parent (str): + Required. Parent resource + Format: + + organizations/{organization}/locations/{location}/customers/{customer} + + 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.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.pagers.ListWorkloadsPager: + Response message for list customer + workloads requests. + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a customer_workloads.ListWorkloadsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, customer_workloads.ListWorkloadsRequest): + request = customer_workloads.ListWorkloadsRequest(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_workloads] + + # 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.ListWorkloadsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_customer( + self, + request: Optional[Union[customers.GetCustomerRequest, 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]] = (), + ) -> customers.Customer: + r"""Gets details of a single customer + + .. 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 cloudcontrolspartner_v1beta + + def sample_get_customer(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetCustomerRequest( + name="name_value", + ) + + # Make the request + response = client.get_customer(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1beta.types.GetCustomerRequest, dict]): + The request object. Message for getting a customer + name (str): + Required. Format: + + organizations/{organization}/locations/{location}/customers/{customer} + + 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.cloudcontrolspartner_v1beta.types.Customer: + Contains metadata around a Cloud + Controls Partner Customer + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a customers.GetCustomerRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, customers.GetCustomerRequest): + request = customers.GetCustomerRequest(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_customer] + + # 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_customers( + self, + request: Optional[Union[customers.ListCustomersRequest, 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.ListCustomersPager: + r"""Lists customers of a partner identified by its Google + Cloud organization ID + + .. 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 cloudcontrolspartner_v1beta + + def sample_list_customers(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.ListCustomersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_customers(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1beta.types.ListCustomersRequest, dict]): + The request object. Request to list customers + parent (str): + Required. Parent resource + Format: + organizations/{organization}/locations/{location} + + 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.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.pagers.ListCustomersPager: + Response message for list customer + Customers requests + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a customers.ListCustomersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, customers.ListCustomersRequest): + request = customers.ListCustomersRequest(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_customers] + + # 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.ListCustomersPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_ekm_connections( + self, + request: Optional[Union[ekm_connections.GetEkmConnectionsRequest, 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]] = (), + ) -> ekm_connections.EkmConnections: + r"""Gets the EKM connections associated with a workload + + .. 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 cloudcontrolspartner_v1beta + + def sample_get_ekm_connections(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetEkmConnectionsRequest( + name="name_value", + ) + + # Make the request + response = client.get_ekm_connections(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1beta.types.GetEkmConnectionsRequest, dict]): + The request object. Request for getting the EKM + connections associated with a workload + name (str): + Required. Format: + + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/ekmConnections + + 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.cloudcontrolspartner_v1beta.types.EkmConnections: + The EKM connections associated with a + workload + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a ekm_connections.GetEkmConnectionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, ekm_connections.GetEkmConnectionsRequest): + request = ekm_connections.GetEkmConnectionsRequest(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_ekm_connections] + + # 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 get_partner_permissions( + self, + request: Optional[ + Union[partner_permissions.GetPartnerPermissionsRequest, 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]] = (), + ) -> partner_permissions.PartnerPermissions: + r"""Gets the partner permissions granted for a workload + + .. 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 cloudcontrolspartner_v1beta + + def sample_get_partner_permissions(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetPartnerPermissionsRequest( + name="name_value", + ) + + # Make the request + response = client.get_partner_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1beta.types.GetPartnerPermissionsRequest, dict]): + The request object. Request for getting the partner + permissions granted for a workload + name (str): + Required. Name of the resource to get + in the format: + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/partnerPermissions + + 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.cloudcontrolspartner_v1beta.types.PartnerPermissions: + The permissions granted to the + partner for a workload + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a partner_permissions.GetPartnerPermissionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, partner_permissions.GetPartnerPermissionsRequest): + request = partner_permissions.GetPartnerPermissionsRequest(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_partner_permissions] + + # 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_access_approval_requests( + self, + request: Optional[ + Union[access_approval_requests.ListAccessApprovalRequestsRequest, 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.ListAccessApprovalRequestsPager: + r"""Lists access requests associated with a workload + + .. 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 cloudcontrolspartner_v1beta + + def sample_list_access_approval_requests(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.ListAccessApprovalRequestsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_access_approval_requests(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1beta.types.ListAccessApprovalRequestsRequest, dict]): + The request object. Request for getting the access + requests associated with a workload. + parent (str): + Required. Parent resource + Format: + + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload} + + 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.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.pagers.ListAccessApprovalRequestsPager: + Response message for list access + requests. + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a access_approval_requests.ListAccessApprovalRequestsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, access_approval_requests.ListAccessApprovalRequestsRequest + ): + request = access_approval_requests.ListAccessApprovalRequestsRequest( + 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_access_approval_requests + ] + + # 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.ListAccessApprovalRequestsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_partner( + self, + request: Optional[Union[partners.GetPartnerRequest, 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]] = (), + ) -> partners.Partner: + r"""Get details of a Partner. + + .. 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 cloudcontrolspartner_v1beta + + def sample_get_partner(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetPartnerRequest( + name="name_value", + ) + + # Make the request + response = client.get_partner(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1beta.types.GetPartnerRequest, dict]): + The request object. Message for getting a Partner + name (str): + Required. Format: + organizations/{organization}/locations/{location}/partner + + 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.cloudcontrolspartner_v1beta.types.Partner: + Message describing Partner 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a partners.GetPartnerRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, partners.GetPartnerRequest): + request = partners.GetPartnerRequest(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_partner] + + # 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 __enter__(self) -> "CloudControlsPartnerCoreClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("CloudControlsPartnerCoreClient",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/pagers.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/pagers.py new file mode 100644 index 000000000000..b742948298e5 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/pagers.py @@ -0,0 +1,429 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.cloudcontrolspartner_v1beta.types import ( + access_approval_requests, + customer_workloads, + customers, +) + + +class ListWorkloadsPager: + """A pager for iterating through ``list_workloads`` requests. + + This class thinly wraps an initial + :class:`google.cloud.cloudcontrolspartner_v1beta.types.ListWorkloadsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``workloads`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListWorkloads`` requests and continue to iterate + through the ``workloads`` field on the + corresponding responses. + + All the usual :class:`google.cloud.cloudcontrolspartner_v1beta.types.ListWorkloadsResponse` + 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[..., customer_workloads.ListWorkloadsResponse], + request: customer_workloads.ListWorkloadsRequest, + response: customer_workloads.ListWorkloadsResponse, + *, + 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.cloudcontrolspartner_v1beta.types.ListWorkloadsRequest): + The initial request object. + response (google.cloud.cloudcontrolspartner_v1beta.types.ListWorkloadsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = customer_workloads.ListWorkloadsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[customer_workloads.ListWorkloadsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[customer_workloads.Workload]: + for page in self.pages: + yield from page.workloads + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListWorkloadsAsyncPager: + """A pager for iterating through ``list_workloads`` requests. + + This class thinly wraps an initial + :class:`google.cloud.cloudcontrolspartner_v1beta.types.ListWorkloadsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``workloads`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListWorkloads`` requests and continue to iterate + through the ``workloads`` field on the + corresponding responses. + + All the usual :class:`google.cloud.cloudcontrolspartner_v1beta.types.ListWorkloadsResponse` + 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[customer_workloads.ListWorkloadsResponse]], + request: customer_workloads.ListWorkloadsRequest, + response: customer_workloads.ListWorkloadsResponse, + *, + 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.cloudcontrolspartner_v1beta.types.ListWorkloadsRequest): + The initial request object. + response (google.cloud.cloudcontrolspartner_v1beta.types.ListWorkloadsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = customer_workloads.ListWorkloadsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[customer_workloads.ListWorkloadsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[customer_workloads.Workload]: + async def async_generator(): + async for page in self.pages: + for response in page.workloads: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListCustomersPager: + """A pager for iterating through ``list_customers`` requests. + + This class thinly wraps an initial + :class:`google.cloud.cloudcontrolspartner_v1beta.types.ListCustomersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``customers`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCustomers`` requests and continue to iterate + through the ``customers`` field on the + corresponding responses. + + All the usual :class:`google.cloud.cloudcontrolspartner_v1beta.types.ListCustomersResponse` + 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[..., customers.ListCustomersResponse], + request: customers.ListCustomersRequest, + response: customers.ListCustomersResponse, + *, + 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.cloudcontrolspartner_v1beta.types.ListCustomersRequest): + The initial request object. + response (google.cloud.cloudcontrolspartner_v1beta.types.ListCustomersResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = customers.ListCustomersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[customers.ListCustomersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[customers.Customer]: + for page in self.pages: + yield from page.customers + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListCustomersAsyncPager: + """A pager for iterating through ``list_customers`` requests. + + This class thinly wraps an initial + :class:`google.cloud.cloudcontrolspartner_v1beta.types.ListCustomersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``customers`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCustomers`` requests and continue to iterate + through the ``customers`` field on the + corresponding responses. + + All the usual :class:`google.cloud.cloudcontrolspartner_v1beta.types.ListCustomersResponse` + 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[customers.ListCustomersResponse]], + request: customers.ListCustomersRequest, + response: customers.ListCustomersResponse, + *, + 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.cloudcontrolspartner_v1beta.types.ListCustomersRequest): + The initial request object. + response (google.cloud.cloudcontrolspartner_v1beta.types.ListCustomersResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = customers.ListCustomersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[customers.ListCustomersResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[customers.Customer]: + async def async_generator(): + async for page in self.pages: + for response in page.customers: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAccessApprovalRequestsPager: + """A pager for iterating through ``list_access_approval_requests`` requests. + + This class thinly wraps an initial + :class:`google.cloud.cloudcontrolspartner_v1beta.types.ListAccessApprovalRequestsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``access_approval_requests`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAccessApprovalRequests`` requests and continue to iterate + through the ``access_approval_requests`` field on the + corresponding responses. + + All the usual :class:`google.cloud.cloudcontrolspartner_v1beta.types.ListAccessApprovalRequestsResponse` + 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[ + ..., access_approval_requests.ListAccessApprovalRequestsResponse + ], + request: access_approval_requests.ListAccessApprovalRequestsRequest, + response: access_approval_requests.ListAccessApprovalRequestsResponse, + *, + 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.cloudcontrolspartner_v1beta.types.ListAccessApprovalRequestsRequest): + The initial request object. + response (google.cloud.cloudcontrolspartner_v1beta.types.ListAccessApprovalRequestsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = access_approval_requests.ListAccessApprovalRequestsRequest( + request + ) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[access_approval_requests.ListAccessApprovalRequestsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[access_approval_requests.AccessApprovalRequest]: + for page in self.pages: + yield from page.access_approval_requests + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAccessApprovalRequestsAsyncPager: + """A pager for iterating through ``list_access_approval_requests`` requests. + + This class thinly wraps an initial + :class:`google.cloud.cloudcontrolspartner_v1beta.types.ListAccessApprovalRequestsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``access_approval_requests`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAccessApprovalRequests`` requests and continue to iterate + through the ``access_approval_requests`` field on the + corresponding responses. + + All the usual :class:`google.cloud.cloudcontrolspartner_v1beta.types.ListAccessApprovalRequestsResponse` + 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[access_approval_requests.ListAccessApprovalRequestsResponse] + ], + request: access_approval_requests.ListAccessApprovalRequestsRequest, + response: access_approval_requests.ListAccessApprovalRequestsResponse, + *, + 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.cloudcontrolspartner_v1beta.types.ListAccessApprovalRequestsRequest): + The initial request object. + response (google.cloud.cloudcontrolspartner_v1beta.types.ListAccessApprovalRequestsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = access_approval_requests.ListAccessApprovalRequestsRequest( + request + ) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[access_approval_requests.ListAccessApprovalRequestsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterator[access_approval_requests.AccessApprovalRequest]: + async def async_generator(): + async for page in self.pages: + for response in page.access_approval_requests: + 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-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/transports/__init__.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/transports/__init__.py new file mode 100644 index 000000000000..932a6f5d3fd5 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/transports/__init__.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CloudControlsPartnerCoreTransport +from .grpc import CloudControlsPartnerCoreGrpcTransport +from .grpc_asyncio import CloudControlsPartnerCoreGrpcAsyncIOTransport +from .rest import ( + CloudControlsPartnerCoreRestInterceptor, + CloudControlsPartnerCoreRestTransport, +) + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[CloudControlsPartnerCoreTransport]] +_transport_registry["grpc"] = CloudControlsPartnerCoreGrpcTransport +_transport_registry["grpc_asyncio"] = CloudControlsPartnerCoreGrpcAsyncIOTransport +_transport_registry["rest"] = CloudControlsPartnerCoreRestTransport + +__all__ = ( + "CloudControlsPartnerCoreTransport", + "CloudControlsPartnerCoreGrpcTransport", + "CloudControlsPartnerCoreGrpcAsyncIOTransport", + "CloudControlsPartnerCoreRestTransport", + "CloudControlsPartnerCoreRestInterceptor", +) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/transports/base.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/transports/base.py new file mode 100644 index 000000000000..ef3d69228161 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/transports/base.py @@ -0,0 +1,340 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.cloudcontrolspartner_v1beta import gapic_version as package_version +from google.cloud.cloudcontrolspartner_v1beta.types import ( + access_approval_requests, + customer_workloads, + customers, + ekm_connections, + partner_permissions, + partners, +) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class CloudControlsPartnerCoreTransport(abc.ABC): + """Abstract transport class for CloudControlsPartnerCore.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "cloudcontrolspartner.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudcontrolspartner.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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_workload: gapic_v1.method.wrap_method( + self.get_workload, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_workloads: gapic_v1.method.wrap_method( + self.list_workloads, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_customer: gapic_v1.method.wrap_method( + self.get_customer, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_customers: gapic_v1.method.wrap_method( + self.list_customers, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_ekm_connections: gapic_v1.method.wrap_method( + self.get_ekm_connections, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_partner_permissions: gapic_v1.method.wrap_method( + self.get_partner_permissions, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_access_approval_requests: gapic_v1.method.wrap_method( + self.list_access_approval_requests, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_partner: gapic_v1.method.wrap_method( + self.get_partner, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_workload( + self, + ) -> Callable[ + [customer_workloads.GetWorkloadRequest], + Union[customer_workloads.Workload, Awaitable[customer_workloads.Workload]], + ]: + raise NotImplementedError() + + @property + def list_workloads( + self, + ) -> Callable[ + [customer_workloads.ListWorkloadsRequest], + Union[ + customer_workloads.ListWorkloadsResponse, + Awaitable[customer_workloads.ListWorkloadsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_customer( + self, + ) -> Callable[ + [customers.GetCustomerRequest], + Union[customers.Customer, Awaitable[customers.Customer]], + ]: + raise NotImplementedError() + + @property + def list_customers( + self, + ) -> Callable[ + [customers.ListCustomersRequest], + Union[ + customers.ListCustomersResponse, Awaitable[customers.ListCustomersResponse] + ], + ]: + raise NotImplementedError() + + @property + def get_ekm_connections( + self, + ) -> Callable[ + [ekm_connections.GetEkmConnectionsRequest], + Union[ + ekm_connections.EkmConnections, Awaitable[ekm_connections.EkmConnections] + ], + ]: + raise NotImplementedError() + + @property + def get_partner_permissions( + self, + ) -> Callable[ + [partner_permissions.GetPartnerPermissionsRequest], + Union[ + partner_permissions.PartnerPermissions, + Awaitable[partner_permissions.PartnerPermissions], + ], + ]: + raise NotImplementedError() + + @property + def list_access_approval_requests( + self, + ) -> Callable[ + [access_approval_requests.ListAccessApprovalRequestsRequest], + Union[ + access_approval_requests.ListAccessApprovalRequestsResponse, + Awaitable[access_approval_requests.ListAccessApprovalRequestsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_partner( + self, + ) -> Callable[ + [partners.GetPartnerRequest], + Union[partners.Partner, Awaitable[partners.Partner]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("CloudControlsPartnerCoreTransport",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/transports/grpc.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/transports/grpc.py new file mode 100644 index 000000000000..1b820f6679bf --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/transports/grpc.py @@ -0,0 +1,466 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import grpc # type: ignore + +from google.cloud.cloudcontrolspartner_v1beta.types import ( + access_approval_requests, + customer_workloads, + customers, + ekm_connections, + partner_permissions, + partners, +) + +from .base import DEFAULT_CLIENT_INFO, CloudControlsPartnerCoreTransport + + +class CloudControlsPartnerCoreGrpcTransport(CloudControlsPartnerCoreTransport): + """gRPC backend transport for CloudControlsPartnerCore. + + Service describing handlers for resources + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "cloudcontrolspartner.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudcontrolspartner.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. + This argument is ignored if ``channel`` is provided. + 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. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "cloudcontrolspartner.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def get_workload( + self, + ) -> Callable[[customer_workloads.GetWorkloadRequest], customer_workloads.Workload]: + r"""Return a callable for the get workload method over gRPC. + + Gets details of a single workload + + Returns: + Callable[[~.GetWorkloadRequest], + ~.Workload]: + 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_workload" not in self._stubs: + self._stubs["get_workload"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore/GetWorkload", + request_serializer=customer_workloads.GetWorkloadRequest.serialize, + response_deserializer=customer_workloads.Workload.deserialize, + ) + return self._stubs["get_workload"] + + @property + def list_workloads( + self, + ) -> Callable[ + [customer_workloads.ListWorkloadsRequest], + customer_workloads.ListWorkloadsResponse, + ]: + r"""Return a callable for the list workloads method over gRPC. + + Lists customer workloads for a given customer org id + + Returns: + Callable[[~.ListWorkloadsRequest], + ~.ListWorkloadsResponse]: + 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_workloads" not in self._stubs: + self._stubs["list_workloads"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore/ListWorkloads", + request_serializer=customer_workloads.ListWorkloadsRequest.serialize, + response_deserializer=customer_workloads.ListWorkloadsResponse.deserialize, + ) + return self._stubs["list_workloads"] + + @property + def get_customer( + self, + ) -> Callable[[customers.GetCustomerRequest], customers.Customer]: + r"""Return a callable for the get customer method over gRPC. + + Gets details of a single customer + + Returns: + Callable[[~.GetCustomerRequest], + ~.Customer]: + 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_customer" not in self._stubs: + self._stubs["get_customer"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore/GetCustomer", + request_serializer=customers.GetCustomerRequest.serialize, + response_deserializer=customers.Customer.deserialize, + ) + return self._stubs["get_customer"] + + @property + def list_customers( + self, + ) -> Callable[[customers.ListCustomersRequest], customers.ListCustomersResponse]: + r"""Return a callable for the list customers method over gRPC. + + Lists customers of a partner identified by its Google + Cloud organization ID + + Returns: + Callable[[~.ListCustomersRequest], + ~.ListCustomersResponse]: + 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_customers" not in self._stubs: + self._stubs["list_customers"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore/ListCustomers", + request_serializer=customers.ListCustomersRequest.serialize, + response_deserializer=customers.ListCustomersResponse.deserialize, + ) + return self._stubs["list_customers"] + + @property + def get_ekm_connections( + self, + ) -> Callable[ + [ekm_connections.GetEkmConnectionsRequest], ekm_connections.EkmConnections + ]: + r"""Return a callable for the get ekm connections method over gRPC. + + Gets the EKM connections associated with a workload + + Returns: + Callable[[~.GetEkmConnectionsRequest], + ~.EkmConnections]: + 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_ekm_connections" not in self._stubs: + self._stubs["get_ekm_connections"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore/GetEkmConnections", + request_serializer=ekm_connections.GetEkmConnectionsRequest.serialize, + response_deserializer=ekm_connections.EkmConnections.deserialize, + ) + return self._stubs["get_ekm_connections"] + + @property + def get_partner_permissions( + self, + ) -> Callable[ + [partner_permissions.GetPartnerPermissionsRequest], + partner_permissions.PartnerPermissions, + ]: + r"""Return a callable for the get partner permissions method over gRPC. + + Gets the partner permissions granted for a workload + + Returns: + Callable[[~.GetPartnerPermissionsRequest], + ~.PartnerPermissions]: + 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_partner_permissions" not in self._stubs: + self._stubs["get_partner_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore/GetPartnerPermissions", + request_serializer=partner_permissions.GetPartnerPermissionsRequest.serialize, + response_deserializer=partner_permissions.PartnerPermissions.deserialize, + ) + return self._stubs["get_partner_permissions"] + + @property + def list_access_approval_requests( + self, + ) -> Callable[ + [access_approval_requests.ListAccessApprovalRequestsRequest], + access_approval_requests.ListAccessApprovalRequestsResponse, + ]: + r"""Return a callable for the list access approval requests method over gRPC. + + Lists access requests associated with a workload + + Returns: + Callable[[~.ListAccessApprovalRequestsRequest], + ~.ListAccessApprovalRequestsResponse]: + 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_access_approval_requests" not in self._stubs: + self._stubs[ + "list_access_approval_requests" + ] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore/ListAccessApprovalRequests", + request_serializer=access_approval_requests.ListAccessApprovalRequestsRequest.serialize, + response_deserializer=access_approval_requests.ListAccessApprovalRequestsResponse.deserialize, + ) + return self._stubs["list_access_approval_requests"] + + @property + def get_partner(self) -> Callable[[partners.GetPartnerRequest], partners.Partner]: + r"""Return a callable for the get partner method over gRPC. + + Get details of a Partner. + + Returns: + Callable[[~.GetPartnerRequest], + ~.Partner]: + 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_partner" not in self._stubs: + self._stubs["get_partner"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore/GetPartner", + request_serializer=partners.GetPartnerRequest.serialize, + response_deserializer=partners.Partner.deserialize, + ) + return self._stubs["get_partner"] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("CloudControlsPartnerCoreGrpcTransport",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/transports/grpc_asyncio.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/transports/grpc_asyncio.py new file mode 100644 index 000000000000..499b7a63c8ec --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/transports/grpc_asyncio.py @@ -0,0 +1,472 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.cloudcontrolspartner_v1beta.types import ( + access_approval_requests, + customer_workloads, + customers, + ekm_connections, + partner_permissions, + partners, +) + +from .base import DEFAULT_CLIENT_INFO, CloudControlsPartnerCoreTransport +from .grpc import CloudControlsPartnerCoreGrpcTransport + + +class CloudControlsPartnerCoreGrpcAsyncIOTransport(CloudControlsPartnerCoreTransport): + """gRPC AsyncIO backend transport for CloudControlsPartnerCore. + + Service describing handlers for resources + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "cloudcontrolspartner.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudcontrolspartner.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudcontrolspartner.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. + This argument is ignored if ``channel`` is provided. + 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_workload( + self, + ) -> Callable[ + [customer_workloads.GetWorkloadRequest], Awaitable[customer_workloads.Workload] + ]: + r"""Return a callable for the get workload method over gRPC. + + Gets details of a single workload + + Returns: + Callable[[~.GetWorkloadRequest], + Awaitable[~.Workload]]: + 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_workload" not in self._stubs: + self._stubs["get_workload"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore/GetWorkload", + request_serializer=customer_workloads.GetWorkloadRequest.serialize, + response_deserializer=customer_workloads.Workload.deserialize, + ) + return self._stubs["get_workload"] + + @property + def list_workloads( + self, + ) -> Callable[ + [customer_workloads.ListWorkloadsRequest], + Awaitable[customer_workloads.ListWorkloadsResponse], + ]: + r"""Return a callable for the list workloads method over gRPC. + + Lists customer workloads for a given customer org id + + Returns: + Callable[[~.ListWorkloadsRequest], + Awaitable[~.ListWorkloadsResponse]]: + 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_workloads" not in self._stubs: + self._stubs["list_workloads"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore/ListWorkloads", + request_serializer=customer_workloads.ListWorkloadsRequest.serialize, + response_deserializer=customer_workloads.ListWorkloadsResponse.deserialize, + ) + return self._stubs["list_workloads"] + + @property + def get_customer( + self, + ) -> Callable[[customers.GetCustomerRequest], Awaitable[customers.Customer]]: + r"""Return a callable for the get customer method over gRPC. + + Gets details of a single customer + + Returns: + Callable[[~.GetCustomerRequest], + Awaitable[~.Customer]]: + 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_customer" not in self._stubs: + self._stubs["get_customer"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore/GetCustomer", + request_serializer=customers.GetCustomerRequest.serialize, + response_deserializer=customers.Customer.deserialize, + ) + return self._stubs["get_customer"] + + @property + def list_customers( + self, + ) -> Callable[ + [customers.ListCustomersRequest], Awaitable[customers.ListCustomersResponse] + ]: + r"""Return a callable for the list customers method over gRPC. + + Lists customers of a partner identified by its Google + Cloud organization ID + + Returns: + Callable[[~.ListCustomersRequest], + Awaitable[~.ListCustomersResponse]]: + 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_customers" not in self._stubs: + self._stubs["list_customers"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore/ListCustomers", + request_serializer=customers.ListCustomersRequest.serialize, + response_deserializer=customers.ListCustomersResponse.deserialize, + ) + return self._stubs["list_customers"] + + @property + def get_ekm_connections( + self, + ) -> Callable[ + [ekm_connections.GetEkmConnectionsRequest], + Awaitable[ekm_connections.EkmConnections], + ]: + r"""Return a callable for the get ekm connections method over gRPC. + + Gets the EKM connections associated with a workload + + Returns: + Callable[[~.GetEkmConnectionsRequest], + Awaitable[~.EkmConnections]]: + 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_ekm_connections" not in self._stubs: + self._stubs["get_ekm_connections"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore/GetEkmConnections", + request_serializer=ekm_connections.GetEkmConnectionsRequest.serialize, + response_deserializer=ekm_connections.EkmConnections.deserialize, + ) + return self._stubs["get_ekm_connections"] + + @property + def get_partner_permissions( + self, + ) -> Callable[ + [partner_permissions.GetPartnerPermissionsRequest], + Awaitable[partner_permissions.PartnerPermissions], + ]: + r"""Return a callable for the get partner permissions method over gRPC. + + Gets the partner permissions granted for a workload + + Returns: + Callable[[~.GetPartnerPermissionsRequest], + Awaitable[~.PartnerPermissions]]: + 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_partner_permissions" not in self._stubs: + self._stubs["get_partner_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore/GetPartnerPermissions", + request_serializer=partner_permissions.GetPartnerPermissionsRequest.serialize, + response_deserializer=partner_permissions.PartnerPermissions.deserialize, + ) + return self._stubs["get_partner_permissions"] + + @property + def list_access_approval_requests( + self, + ) -> Callable[ + [access_approval_requests.ListAccessApprovalRequestsRequest], + Awaitable[access_approval_requests.ListAccessApprovalRequestsResponse], + ]: + r"""Return a callable for the list access approval requests method over gRPC. + + Lists access requests associated with a workload + + Returns: + Callable[[~.ListAccessApprovalRequestsRequest], + Awaitable[~.ListAccessApprovalRequestsResponse]]: + 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_access_approval_requests" not in self._stubs: + self._stubs[ + "list_access_approval_requests" + ] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore/ListAccessApprovalRequests", + request_serializer=access_approval_requests.ListAccessApprovalRequestsRequest.serialize, + response_deserializer=access_approval_requests.ListAccessApprovalRequestsResponse.deserialize, + ) + return self._stubs["list_access_approval_requests"] + + @property + def get_partner( + self, + ) -> Callable[[partners.GetPartnerRequest], Awaitable[partners.Partner]]: + r"""Return a callable for the get partner method over gRPC. + + Get details of a Partner. + + Returns: + Callable[[~.GetPartnerRequest], + Awaitable[~.Partner]]: + 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_partner" not in self._stubs: + self._stubs["get_partner"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore/GetPartner", + request_serializer=partners.GetPartnerRequest.serialize, + response_deserializer=partners.Partner.deserialize, + ) + return self._stubs["get_partner"] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ("CloudControlsPartnerCoreGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/transports/rest.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/transports/rest.py new file mode 100644 index 000000000000..b6a830687480 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_core/transports/rest.py @@ -0,0 +1,1212 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.cloudcontrolspartner_v1beta.types import ( + access_approval_requests, + customer_workloads, + customers, + ekm_connections, + partner_permissions, + partners, +) + +from .base import CloudControlsPartnerCoreTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class CloudControlsPartnerCoreRestInterceptor: + """Interceptor for CloudControlsPartnerCore. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the CloudControlsPartnerCoreRestTransport. + + .. code-block:: python + class MyCustomCloudControlsPartnerCoreInterceptor(CloudControlsPartnerCoreRestInterceptor): + def pre_get_customer(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_customer(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_ekm_connections(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_ekm_connections(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_partner(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_partner(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_partner_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_partner_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_workload(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_workload(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_access_approval_requests(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_access_approval_requests(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_customers(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_customers(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_workloads(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_workloads(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CloudControlsPartnerCoreRestTransport(interceptor=MyCustomCloudControlsPartnerCoreInterceptor()) + client = CloudControlsPartnerCoreClient(transport=transport) + + + """ + + def pre_get_customer( + self, request: customers.GetCustomerRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[customers.GetCustomerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_customer + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerCore server. + """ + return request, metadata + + def post_get_customer(self, response: customers.Customer) -> customers.Customer: + """Post-rpc interceptor for get_customer + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerCore server but before + it is returned to user code. + """ + return response + + def pre_get_ekm_connections( + self, + request: ekm_connections.GetEkmConnectionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ekm_connections.GetEkmConnectionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_ekm_connections + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerCore server. + """ + return request, metadata + + def post_get_ekm_connections( + self, response: ekm_connections.EkmConnections + ) -> ekm_connections.EkmConnections: + """Post-rpc interceptor for get_ekm_connections + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerCore server but before + it is returned to user code. + """ + return response + + def pre_get_partner( + self, request: partners.GetPartnerRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[partners.GetPartnerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_partner + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerCore server. + """ + return request, metadata + + def post_get_partner(self, response: partners.Partner) -> partners.Partner: + """Post-rpc interceptor for get_partner + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerCore server but before + it is returned to user code. + """ + return response + + def pre_get_partner_permissions( + self, + request: partner_permissions.GetPartnerPermissionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + partner_permissions.GetPartnerPermissionsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for get_partner_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerCore server. + """ + return request, metadata + + def post_get_partner_permissions( + self, response: partner_permissions.PartnerPermissions + ) -> partner_permissions.PartnerPermissions: + """Post-rpc interceptor for get_partner_permissions + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerCore server but before + it is returned to user code. + """ + return response + + def pre_get_workload( + self, + request: customer_workloads.GetWorkloadRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[customer_workloads.GetWorkloadRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_workload + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerCore server. + """ + return request, metadata + + def post_get_workload( + self, response: customer_workloads.Workload + ) -> customer_workloads.Workload: + """Post-rpc interceptor for get_workload + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerCore server but before + it is returned to user code. + """ + return response + + def pre_list_access_approval_requests( + self, + request: access_approval_requests.ListAccessApprovalRequestsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + access_approval_requests.ListAccessApprovalRequestsRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for list_access_approval_requests + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerCore server. + """ + return request, metadata + + def post_list_access_approval_requests( + self, response: access_approval_requests.ListAccessApprovalRequestsResponse + ) -> access_approval_requests.ListAccessApprovalRequestsResponse: + """Post-rpc interceptor for list_access_approval_requests + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerCore server but before + it is returned to user code. + """ + return response + + def pre_list_customers( + self, + request: customers.ListCustomersRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[customers.ListCustomersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_customers + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerCore server. + """ + return request, metadata + + def post_list_customers( + self, response: customers.ListCustomersResponse + ) -> customers.ListCustomersResponse: + """Post-rpc interceptor for list_customers + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerCore server but before + it is returned to user code. + """ + return response + + def pre_list_workloads( + self, + request: customer_workloads.ListWorkloadsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[customer_workloads.ListWorkloadsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_workloads + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerCore server. + """ + return request, metadata + + def post_list_workloads( + self, response: customer_workloads.ListWorkloadsResponse + ) -> customer_workloads.ListWorkloadsResponse: + """Post-rpc interceptor for list_workloads + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerCore server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class CloudControlsPartnerCoreRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CloudControlsPartnerCoreRestInterceptor + + +class CloudControlsPartnerCoreRestTransport(CloudControlsPartnerCoreTransport): + """REST backend transport for CloudControlsPartnerCore. + + Service describing handlers for resources + + 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 = "cloudcontrolspartner.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[CloudControlsPartnerCoreRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudcontrolspartner.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 + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or CloudControlsPartnerCoreRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetCustomer(CloudControlsPartnerCoreRestStub): + def __hash__(self): + return hash("GetCustomer") + + __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 + } + + def __call__( + self, + request: customers.GetCustomerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> customers.Customer: + r"""Call the get customer method over HTTP. + + Args: + request (~.customers.GetCustomerRequest): + The request object. Message for getting a customer + 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: + ~.customers.Customer: + Contains metadata around a Cloud + Controls Partner Customer + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=organizations/*/locations/*/customers/*}", + }, + ] + request, metadata = self._interceptor.pre_get_customer(request, metadata) + pb_request = customers.GetCustomerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = customers.Customer() + pb_resp = customers.Customer.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_customer(resp) + return resp + + class _GetEkmConnections(CloudControlsPartnerCoreRestStub): + def __hash__(self): + return hash("GetEkmConnections") + + __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 + } + + def __call__( + self, + request: ekm_connections.GetEkmConnectionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_connections.EkmConnections: + r"""Call the get ekm connections method over HTTP. + + Args: + request (~.ekm_connections.GetEkmConnectionsRequest): + The request object. Request for getting the EKM + connections associated with a workload + 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: + ~.ekm_connections.EkmConnections: + The EKM connections associated with a + workload + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=organizations/*/locations/*/customers/*/workloads/*/ekmConnections}", + }, + ] + request, metadata = self._interceptor.pre_get_ekm_connections( + request, metadata + ) + pb_request = ekm_connections.GetEkmConnectionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = ekm_connections.EkmConnections() + pb_resp = ekm_connections.EkmConnections.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_ekm_connections(resp) + return resp + + class _GetPartner(CloudControlsPartnerCoreRestStub): + def __hash__(self): + return hash("GetPartner") + + __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 + } + + def __call__( + self, + request: partners.GetPartnerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> partners.Partner: + r"""Call the get partner method over HTTP. + + Args: + request (~.partners.GetPartnerRequest): + The request object. Message for getting a Partner + 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: + ~.partners.Partner: + Message describing Partner resource + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=organizations/*/locations/*/partner}", + }, + ] + request, metadata = self._interceptor.pre_get_partner(request, metadata) + pb_request = partners.GetPartnerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = partners.Partner() + pb_resp = partners.Partner.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_partner(resp) + return resp + + class _GetPartnerPermissions(CloudControlsPartnerCoreRestStub): + def __hash__(self): + return hash("GetPartnerPermissions") + + __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 + } + + def __call__( + self, + request: partner_permissions.GetPartnerPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> partner_permissions.PartnerPermissions: + r"""Call the get partner permissions method over HTTP. + + Args: + request (~.partner_permissions.GetPartnerPermissionsRequest): + The request object. Request for getting the partner + permissions granted for a workload + 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: + ~.partner_permissions.PartnerPermissions: + The permissions granted to the + partner for a workload + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=organizations/*/locations/*/customers/*/workloads/*/partnerPermissions}", + }, + ] + request, metadata = self._interceptor.pre_get_partner_permissions( + request, metadata + ) + pb_request = partner_permissions.GetPartnerPermissionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = partner_permissions.PartnerPermissions() + pb_resp = partner_permissions.PartnerPermissions.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_partner_permissions(resp) + return resp + + class _GetWorkload(CloudControlsPartnerCoreRestStub): + def __hash__(self): + return hash("GetWorkload") + + __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 + } + + def __call__( + self, + request: customer_workloads.GetWorkloadRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> customer_workloads.Workload: + r"""Call the get workload method over HTTP. + + Args: + request (~.customer_workloads.GetWorkloadRequest): + The request object. Message for getting a customer + workload. + 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: + ~.customer_workloads.Workload: + Contains metadata around the `Workload + resource `__ + in the Assured Workloads API. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=organizations/*/locations/*/customers/*/workloads/*}", + }, + ] + request, metadata = self._interceptor.pre_get_workload(request, metadata) + pb_request = customer_workloads.GetWorkloadRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = customer_workloads.Workload() + pb_resp = customer_workloads.Workload.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_workload(resp) + return resp + + class _ListAccessApprovalRequests(CloudControlsPartnerCoreRestStub): + def __hash__(self): + return hash("ListAccessApprovalRequests") + + __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 + } + + def __call__( + self, + request: access_approval_requests.ListAccessApprovalRequestsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> access_approval_requests.ListAccessApprovalRequestsResponse: + r"""Call the list access approval + requests method over HTTP. + + Args: + request (~.access_approval_requests.ListAccessApprovalRequestsRequest): + The request object. Request for getting the access + requests associated with a workload. + 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: + ~.access_approval_requests.ListAccessApprovalRequestsResponse: + Response message for list access + requests. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=organizations/*/locations/*/customers/*/workloads/*}/accessApprovalRequests", + }, + ] + request, metadata = self._interceptor.pre_list_access_approval_requests( + request, metadata + ) + pb_request = access_approval_requests.ListAccessApprovalRequestsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = access_approval_requests.ListAccessApprovalRequestsResponse() + pb_resp = access_approval_requests.ListAccessApprovalRequestsResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_access_approval_requests(resp) + return resp + + class _ListCustomers(CloudControlsPartnerCoreRestStub): + def __hash__(self): + return hash("ListCustomers") + + __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 + } + + def __call__( + self, + request: customers.ListCustomersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> customers.ListCustomersResponse: + r"""Call the list customers method over HTTP. + + Args: + request (~.customers.ListCustomersRequest): + The request object. Request to list customers + 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: + ~.customers.ListCustomersResponse: + Response message for list customer + Customers requests + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=organizations/*/locations/*}/customers", + }, + ] + request, metadata = self._interceptor.pre_list_customers(request, metadata) + pb_request = customers.ListCustomersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = customers.ListCustomersResponse() + pb_resp = customers.ListCustomersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_customers(resp) + return resp + + class _ListWorkloads(CloudControlsPartnerCoreRestStub): + def __hash__(self): + return hash("ListWorkloads") + + __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 + } + + def __call__( + self, + request: customer_workloads.ListWorkloadsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> customer_workloads.ListWorkloadsResponse: + r"""Call the list workloads method over HTTP. + + Args: + request (~.customer_workloads.ListWorkloadsRequest): + The request object. Request to list customer workloads. + 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: + ~.customer_workloads.ListWorkloadsResponse: + Response message for list customer + workloads requests. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=organizations/*/locations/*/customers/*}/workloads", + }, + ] + request, metadata = self._interceptor.pre_list_workloads(request, metadata) + pb_request = customer_workloads.ListWorkloadsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = customer_workloads.ListWorkloadsResponse() + pb_resp = customer_workloads.ListWorkloadsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_workloads(resp) + return resp + + @property + def get_customer( + self, + ) -> Callable[[customers.GetCustomerRequest], customers.Customer]: + # 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._GetCustomer(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_ekm_connections( + self, + ) -> Callable[ + [ekm_connections.GetEkmConnectionsRequest], ekm_connections.EkmConnections + ]: + # 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._GetEkmConnections(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_partner(self) -> Callable[[partners.GetPartnerRequest], partners.Partner]: + # 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._GetPartner(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_partner_permissions( + self, + ) -> Callable[ + [partner_permissions.GetPartnerPermissionsRequest], + partner_permissions.PartnerPermissions, + ]: + # 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._GetPartnerPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_workload( + self, + ) -> Callable[[customer_workloads.GetWorkloadRequest], customer_workloads.Workload]: + # 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._GetWorkload(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_access_approval_requests( + self, + ) -> Callable[ + [access_approval_requests.ListAccessApprovalRequestsRequest], + access_approval_requests.ListAccessApprovalRequestsResponse, + ]: + # 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._ListAccessApprovalRequests(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_customers( + self, + ) -> Callable[[customers.ListCustomersRequest], customers.ListCustomersResponse]: + # 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._ListCustomers(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_workloads( + self, + ) -> Callable[ + [customer_workloads.ListWorkloadsRequest], + customer_workloads.ListWorkloadsResponse, + ]: + # 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._ListWorkloads(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("CloudControlsPartnerCoreRestTransport",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/__init__.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/__init__.py new file mode 100644 index 000000000000..28b28fe9ff7f --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .async_client import CloudControlsPartnerMonitoringAsyncClient +from .client import CloudControlsPartnerMonitoringClient + +__all__ = ( + "CloudControlsPartnerMonitoringClient", + "CloudControlsPartnerMonitoringAsyncClient", +) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/async_client.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/async_client.py new file mode 100644 index 000000000000..4c0063fac475 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/async_client.py @@ -0,0 +1,530 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.cloudcontrolspartner_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_monitoring import ( + pagers, +) +from google.cloud.cloudcontrolspartner_v1beta.types import violations + +from .client import CloudControlsPartnerMonitoringClient +from .transports.base import ( + DEFAULT_CLIENT_INFO, + CloudControlsPartnerMonitoringTransport, +) +from .transports.grpc_asyncio import CloudControlsPartnerMonitoringGrpcAsyncIOTransport + + +class CloudControlsPartnerMonitoringAsyncClient: + """Service describing handlers for resources""" + + _client: CloudControlsPartnerMonitoringClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = CloudControlsPartnerMonitoringClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CloudControlsPartnerMonitoringClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ( + CloudControlsPartnerMonitoringClient._DEFAULT_ENDPOINT_TEMPLATE + ) + _DEFAULT_UNIVERSE = CloudControlsPartnerMonitoringClient._DEFAULT_UNIVERSE + + violation_path = staticmethod(CloudControlsPartnerMonitoringClient.violation_path) + parse_violation_path = staticmethod( + CloudControlsPartnerMonitoringClient.parse_violation_path + ) + common_billing_account_path = staticmethod( + CloudControlsPartnerMonitoringClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + CloudControlsPartnerMonitoringClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + CloudControlsPartnerMonitoringClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + CloudControlsPartnerMonitoringClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + CloudControlsPartnerMonitoringClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + CloudControlsPartnerMonitoringClient.parse_common_organization_path + ) + common_project_path = staticmethod( + CloudControlsPartnerMonitoringClient.common_project_path + ) + parse_common_project_path = staticmethod( + CloudControlsPartnerMonitoringClient.parse_common_project_path + ) + common_location_path = staticmethod( + CloudControlsPartnerMonitoringClient.common_location_path + ) + parse_common_location_path = staticmethod( + CloudControlsPartnerMonitoringClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudControlsPartnerMonitoringAsyncClient: The constructed client. + """ + return CloudControlsPartnerMonitoringClient.from_service_account_info.__func__(CloudControlsPartnerMonitoringAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudControlsPartnerMonitoringAsyncClient: The constructed client. + """ + return CloudControlsPartnerMonitoringClient.from_service_account_file.__func__(CloudControlsPartnerMonitoringAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CloudControlsPartnerMonitoringClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CloudControlsPartnerMonitoringTransport: + """Returns the transport used by the client instance. + + Returns: + CloudControlsPartnerMonitoringTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial( + type(CloudControlsPartnerMonitoringClient).get_transport_class, + type(CloudControlsPartnerMonitoringClient), + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CloudControlsPartnerMonitoringTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud controls partner monitoring async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.CloudControlsPartnerMonitoringTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CloudControlsPartnerMonitoringClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_violations( + self, + request: Optional[Union[violations.ListViolationsRequest, 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.ListViolationsAsyncPager: + r"""Lists Violations for a workload Callers may also choose to read + across multiple Customers or for a single customer as per + `AIP-159 `__ by using '-' (the + hyphen or dash character) as a wildcard character instead of + {customer} & {workload}. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + + .. 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 cloudcontrolspartner_v1beta + + async def sample_list_violations(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerMonitoringAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.ListViolationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_violations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1beta.types.ListViolationsRequest, dict]]): + The request object. Message for requesting list of + Violations + parent (:class:`str`): + Required. Parent resource + Format + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload} + + 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.cloudcontrolspartner_v1beta.services.cloud_controls_partner_monitoring.pagers.ListViolationsAsyncPager: + Response message for list customer + violation requests + 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." + ) + + request = violations.ListViolationsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_violations, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListViolationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_violation( + self, + request: Optional[Union[violations.GetViolationRequest, 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]] = (), + ) -> violations.Violation: + r"""Gets details of a single Violation. + + .. 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 cloudcontrolspartner_v1beta + + async def sample_get_violation(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerMonitoringAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetViolationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_violation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.cloudcontrolspartner_v1beta.types.GetViolationRequest, dict]]): + The request object. Message for getting a Violation + name (:class:`str`): + Required. Format: + + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/violations/{violation} + + 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.cloudcontrolspartner_v1beta.types.Violation: + Details of resource Violation + """ + # 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." + ) + + request = violations.GetViolationRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_violation, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 __aenter__(self) -> "CloudControlsPartnerMonitoringAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("CloudControlsPartnerMonitoringAsyncClient",) 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 new file mode 100644 index 000000000000..9a8f28852887 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/client.py @@ -0,0 +1,937 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.cloudcontrolspartner_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_monitoring import ( + pagers, +) +from google.cloud.cloudcontrolspartner_v1beta.types import violations + +from .transports.base import ( + DEFAULT_CLIENT_INFO, + CloudControlsPartnerMonitoringTransport, +) +from .transports.grpc import CloudControlsPartnerMonitoringGrpcTransport +from .transports.grpc_asyncio import CloudControlsPartnerMonitoringGrpcAsyncIOTransport +from .transports.rest import CloudControlsPartnerMonitoringRestTransport + + +class CloudControlsPartnerMonitoringClientMeta(type): + """Metaclass for the CloudControlsPartnerMonitoring client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[CloudControlsPartnerMonitoringTransport]] + _transport_registry["grpc"] = CloudControlsPartnerMonitoringGrpcTransport + _transport_registry[ + "grpc_asyncio" + ] = CloudControlsPartnerMonitoringGrpcAsyncIOTransport + _transport_registry["rest"] = CloudControlsPartnerMonitoringRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[CloudControlsPartnerMonitoringTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class CloudControlsPartnerMonitoringClient( + metaclass=CloudControlsPartnerMonitoringClientMeta +): + """Service describing handlers for resources""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "cloudcontrolspartner.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "cloudcontrolspartner.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudControlsPartnerMonitoringClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CloudControlsPartnerMonitoringClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> CloudControlsPartnerMonitoringTransport: + """Returns the transport used by the client instance. + + Returns: + CloudControlsPartnerMonitoringTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def violation_path( + organization: str, + location: str, + customer: str, + workload: str, + violation: str, + ) -> str: + """Returns a fully-qualified violation string.""" + return "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/violations/{violation}".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + violation=violation, + ) + + @staticmethod + def parse_violation_path(path: str) -> Dict[str, str]: + """Parses a violation path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/customers/(?P.+?)/workloads/(?P.+?)/violations/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = CloudControlsPartnerMonitoringClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = CloudControlsPartnerMonitoringClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + CloudControlsPartnerMonitoringClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = CloudControlsPartnerMonitoringClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + 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. + + Returns: + bool: True iff the configured universe domain is valid. + + 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 + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, CloudControlsPartnerMonitoringTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the cloud controls partner monitoring client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, CloudControlsPartnerMonitoringTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = CloudControlsPartnerMonitoringClient._read_environment_variables() + self._client_cert_source = ( + CloudControlsPartnerMonitoringClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = ( + CloudControlsPartnerMonitoringClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance( + transport, CloudControlsPartnerMonitoringTransport + ) + if transport_provided: + # transport is a CloudControlsPartnerMonitoringTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(CloudControlsPartnerMonitoringTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or CloudControlsPartnerMonitoringClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + Transport = type(self).get_transport_class(cast(str, transport)) + self._transport = Transport( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def list_violations( + self, + request: Optional[Union[violations.ListViolationsRequest, 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.ListViolationsPager: + r"""Lists Violations for a workload Callers may also choose to read + across multiple Customers or for a single customer as per + `AIP-159 `__ by using '-' (the + hyphen or dash character) as a wildcard character instead of + {customer} & {workload}. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + + .. 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 cloudcontrolspartner_v1beta + + def sample_list_violations(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerMonitoringClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.ListViolationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_violations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1beta.types.ListViolationsRequest, dict]): + The request object. Message for requesting list of + Violations + parent (str): + Required. Parent resource + Format + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload} + + 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.cloudcontrolspartner_v1beta.services.cloud_controls_partner_monitoring.pagers.ListViolationsPager: + Response message for list customer + violation requests + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a violations.ListViolationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, violations.ListViolationsRequest): + request = violations.ListViolationsRequest(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_violations] + + # 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.ListViolationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_violation( + self, + request: Optional[Union[violations.GetViolationRequest, 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]] = (), + ) -> violations.Violation: + r"""Gets details of a single Violation. + + .. 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 cloudcontrolspartner_v1beta + + def sample_get_violation(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerMonitoringClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetViolationRequest( + name="name_value", + ) + + # Make the request + response = client.get_violation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.cloudcontrolspartner_v1beta.types.GetViolationRequest, dict]): + The request object. Message for getting a Violation + name (str): + Required. Format: + + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/violations/{violation} + + 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.cloudcontrolspartner_v1beta.types.Violation: + Details of resource Violation + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a violations.GetViolationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, violations.GetViolationRequest): + request = violations.GetViolationRequest(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_violation] + + # 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 __enter__(self) -> "CloudControlsPartnerMonitoringClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("CloudControlsPartnerMonitoringClient",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/pagers.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/pagers.py new file mode 100644 index 000000000000..0b215511279d --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/pagers.py @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.cloudcontrolspartner_v1beta.types import violations + + +class ListViolationsPager: + """A pager for iterating through ``list_violations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.cloudcontrolspartner_v1beta.types.ListViolationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``violations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListViolations`` requests and continue to iterate + through the ``violations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.cloudcontrolspartner_v1beta.types.ListViolationsResponse` + 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[..., violations.ListViolationsResponse], + request: violations.ListViolationsRequest, + response: violations.ListViolationsResponse, + *, + 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.cloudcontrolspartner_v1beta.types.ListViolationsRequest): + The initial request object. + response (google.cloud.cloudcontrolspartner_v1beta.types.ListViolationsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = violations.ListViolationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[violations.ListViolationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[violations.Violation]: + for page in self.pages: + yield from page.violations + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListViolationsAsyncPager: + """A pager for iterating through ``list_violations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.cloudcontrolspartner_v1beta.types.ListViolationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``violations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListViolations`` requests and continue to iterate + through the ``violations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.cloudcontrolspartner_v1beta.types.ListViolationsResponse` + 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[violations.ListViolationsResponse]], + request: violations.ListViolationsRequest, + response: violations.ListViolationsResponse, + *, + 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.cloudcontrolspartner_v1beta.types.ListViolationsRequest): + The initial request object. + response (google.cloud.cloudcontrolspartner_v1beta.types.ListViolationsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = violations.ListViolationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[violations.ListViolationsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[violations.Violation]: + async def async_generator(): + async for page in self.pages: + for response in page.violations: + 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-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/transports/__init__.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/transports/__init__.py new file mode 100644 index 000000000000..d8563cd63e93 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/transports/__init__.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CloudControlsPartnerMonitoringTransport +from .grpc import CloudControlsPartnerMonitoringGrpcTransport +from .grpc_asyncio import CloudControlsPartnerMonitoringGrpcAsyncIOTransport +from .rest import ( + CloudControlsPartnerMonitoringRestInterceptor, + CloudControlsPartnerMonitoringRestTransport, +) + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[CloudControlsPartnerMonitoringTransport]] +_transport_registry["grpc"] = CloudControlsPartnerMonitoringGrpcTransport +_transport_registry["grpc_asyncio"] = CloudControlsPartnerMonitoringGrpcAsyncIOTransport +_transport_registry["rest"] = CloudControlsPartnerMonitoringRestTransport + +__all__ = ( + "CloudControlsPartnerMonitoringTransport", + "CloudControlsPartnerMonitoringGrpcTransport", + "CloudControlsPartnerMonitoringGrpcAsyncIOTransport", + "CloudControlsPartnerMonitoringRestTransport", + "CloudControlsPartnerMonitoringRestInterceptor", +) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/transports/base.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/transports/base.py new file mode 100644 index 000000000000..ec4e35b32bed --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/transports/base.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.cloudcontrolspartner_v1beta import gapic_version as package_version +from google.cloud.cloudcontrolspartner_v1beta.types import violations + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class CloudControlsPartnerMonitoringTransport(abc.ABC): + """Abstract transport class for CloudControlsPartnerMonitoring.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "cloudcontrolspartner.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudcontrolspartner.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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_violations: gapic_v1.method.wrap_method( + self.list_violations, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_violation: gapic_v1.method.wrap_method( + self.get_violation, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_violations( + self, + ) -> Callable[ + [violations.ListViolationsRequest], + Union[ + violations.ListViolationsResponse, + Awaitable[violations.ListViolationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_violation( + self, + ) -> Callable[ + [violations.GetViolationRequest], + Union[violations.Violation, Awaitable[violations.Violation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("CloudControlsPartnerMonitoringTransport",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/transports/grpc.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/transports/grpc.py new file mode 100644 index 000000000000..2a1052a7a5fe --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/transports/grpc.py @@ -0,0 +1,300 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import grpc # type: ignore + +from google.cloud.cloudcontrolspartner_v1beta.types import violations + +from .base import DEFAULT_CLIENT_INFO, CloudControlsPartnerMonitoringTransport + + +class CloudControlsPartnerMonitoringGrpcTransport( + CloudControlsPartnerMonitoringTransport +): + """gRPC backend transport for CloudControlsPartnerMonitoring. + + Service describing handlers for resources + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "cloudcontrolspartner.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudcontrolspartner.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. + This argument is ignored if ``channel`` is provided. + 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. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "cloudcontrolspartner.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def list_violations( + self, + ) -> Callable[ + [violations.ListViolationsRequest], violations.ListViolationsResponse + ]: + r"""Return a callable for the list violations method over gRPC. + + Lists Violations for a workload Callers may also choose to read + across multiple Customers or for a single customer as per + `AIP-159 `__ by using '-' (the + hyphen or dash character) as a wildcard character instead of + {customer} & {workload}. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + + Returns: + Callable[[~.ListViolationsRequest], + ~.ListViolationsResponse]: + 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_violations" not in self._stubs: + self._stubs["list_violations"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerMonitoring/ListViolations", + request_serializer=violations.ListViolationsRequest.serialize, + response_deserializer=violations.ListViolationsResponse.deserialize, + ) + return self._stubs["list_violations"] + + @property + def get_violation( + self, + ) -> Callable[[violations.GetViolationRequest], violations.Violation]: + r"""Return a callable for the get violation method over gRPC. + + Gets details of a single Violation. + + Returns: + Callable[[~.GetViolationRequest], + ~.Violation]: + 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_violation" not in self._stubs: + self._stubs["get_violation"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerMonitoring/GetViolation", + request_serializer=violations.GetViolationRequest.serialize, + response_deserializer=violations.Violation.deserialize, + ) + return self._stubs["get_violation"] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("CloudControlsPartnerMonitoringGrpcTransport",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/transports/grpc_asyncio.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/transports/grpc_asyncio.py new file mode 100644 index 000000000000..e241f5f1dfa9 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/transports/grpc_asyncio.py @@ -0,0 +1,299 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.cloudcontrolspartner_v1beta.types import violations + +from .base import DEFAULT_CLIENT_INFO, CloudControlsPartnerMonitoringTransport +from .grpc import CloudControlsPartnerMonitoringGrpcTransport + + +class CloudControlsPartnerMonitoringGrpcAsyncIOTransport( + CloudControlsPartnerMonitoringTransport +): + """gRPC AsyncIO backend transport for CloudControlsPartnerMonitoring. + + Service describing handlers for resources + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "cloudcontrolspartner.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudcontrolspartner.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudcontrolspartner.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. + This argument is ignored if ``channel`` is provided. + 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_violations( + self, + ) -> Callable[ + [violations.ListViolationsRequest], Awaitable[violations.ListViolationsResponse] + ]: + r"""Return a callable for the list violations method over gRPC. + + Lists Violations for a workload Callers may also choose to read + across multiple Customers or for a single customer as per + `AIP-159 `__ by using '-' (the + hyphen or dash character) as a wildcard character instead of + {customer} & {workload}. Format: + ``organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}`` + + Returns: + Callable[[~.ListViolationsRequest], + Awaitable[~.ListViolationsResponse]]: + 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_violations" not in self._stubs: + self._stubs["list_violations"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerMonitoring/ListViolations", + request_serializer=violations.ListViolationsRequest.serialize, + response_deserializer=violations.ListViolationsResponse.deserialize, + ) + return self._stubs["list_violations"] + + @property + def get_violation( + self, + ) -> Callable[[violations.GetViolationRequest], Awaitable[violations.Violation]]: + r"""Return a callable for the get violation method over gRPC. + + Gets details of a single Violation. + + Returns: + Callable[[~.GetViolationRequest], + Awaitable[~.Violation]]: + 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_violation" not in self._stubs: + self._stubs["get_violation"] = self.grpc_channel.unary_unary( + "/google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerMonitoring/GetViolation", + request_serializer=violations.GetViolationRequest.serialize, + response_deserializer=violations.Violation.deserialize, + ) + return self._stubs["get_violation"] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ("CloudControlsPartnerMonitoringGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/transports/rest.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/transports/rest.py new file mode 100644 index 000000000000..49f2ad7c26b1 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/services/cloud_controls_partner_monitoring/transports/rest.py @@ -0,0 +1,434 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.cloudcontrolspartner_v1beta.types import violations + +from .base import CloudControlsPartnerMonitoringTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class CloudControlsPartnerMonitoringRestInterceptor: + """Interceptor for CloudControlsPartnerMonitoring. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the CloudControlsPartnerMonitoringRestTransport. + + .. code-block:: python + class MyCustomCloudControlsPartnerMonitoringInterceptor(CloudControlsPartnerMonitoringRestInterceptor): + def pre_get_violation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_violation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_violations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_violations(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CloudControlsPartnerMonitoringRestTransport(interceptor=MyCustomCloudControlsPartnerMonitoringInterceptor()) + client = CloudControlsPartnerMonitoringClient(transport=transport) + + + """ + + def pre_get_violation( + self, + request: violations.GetViolationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[violations.GetViolationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_violation + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerMonitoring server. + """ + return request, metadata + + def post_get_violation( + self, response: violations.Violation + ) -> violations.Violation: + """Post-rpc interceptor for get_violation + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerMonitoring server but before + it is returned to user code. + """ + return response + + def pre_list_violations( + self, + request: violations.ListViolationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[violations.ListViolationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_violations + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudControlsPartnerMonitoring server. + """ + return request, metadata + + def post_list_violations( + self, response: violations.ListViolationsResponse + ) -> violations.ListViolationsResponse: + """Post-rpc interceptor for list_violations + + Override in a subclass to manipulate the response + after it is returned by the CloudControlsPartnerMonitoring server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class CloudControlsPartnerMonitoringRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CloudControlsPartnerMonitoringRestInterceptor + + +class CloudControlsPartnerMonitoringRestTransport( + CloudControlsPartnerMonitoringTransport +): + """REST backend transport for CloudControlsPartnerMonitoring. + + Service describing handlers for resources + + 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 = "cloudcontrolspartner.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[CloudControlsPartnerMonitoringRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudcontrolspartner.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 + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = ( + interceptor or CloudControlsPartnerMonitoringRestInterceptor() + ) + self._prep_wrapped_messages(client_info) + + class _GetViolation(CloudControlsPartnerMonitoringRestStub): + def __hash__(self): + return hash("GetViolation") + + __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 + } + + def __call__( + self, + request: violations.GetViolationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> violations.Violation: + r"""Call the get violation method over HTTP. + + Args: + request (~.violations.GetViolationRequest): + The request object. Message for getting a Violation + 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: + ~.violations.Violation: + Details of resource Violation + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=organizations/*/locations/*/customers/*/workloads/*/violations/*}", + }, + ] + request, metadata = self._interceptor.pre_get_violation(request, metadata) + pb_request = violations.GetViolationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = violations.Violation() + pb_resp = violations.Violation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_violation(resp) + return resp + + class _ListViolations(CloudControlsPartnerMonitoringRestStub): + def __hash__(self): + return hash("ListViolations") + + __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 + } + + def __call__( + self, + request: violations.ListViolationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> violations.ListViolationsResponse: + r"""Call the list violations method over HTTP. + + Args: + request (~.violations.ListViolationsRequest): + The request object. Message for requesting list of + Violations + 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: + ~.violations.ListViolationsResponse: + Response message for list customer + violation requests + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=organizations/*/locations/*/customers/*/workloads/*}/violations", + }, + ] + request, metadata = self._interceptor.pre_list_violations(request, metadata) + pb_request = violations.ListViolationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = violations.ListViolationsResponse() + pb_resp = violations.ListViolationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_violations(resp) + return resp + + @property + def get_violation( + self, + ) -> Callable[[violations.GetViolationRequest], violations.Violation]: + # 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._GetViolation(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_violations( + self, + ) -> Callable[ + [violations.ListViolationsRequest], violations.ListViolationsResponse + ]: + # 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._ListViolations(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("CloudControlsPartnerMonitoringRestTransport",) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/__init__.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/__init__.py new file mode 100644 index 000000000000..3a4f3a5a7d64 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/__init__.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .access_approval_requests import ( + AccessApprovalRequest, + AccessReason, + ListAccessApprovalRequestsRequest, + ListAccessApprovalRequestsResponse, +) +from .completion_state import CompletionState +from .core import OperationMetadata +from .customer_workloads import ( + GetWorkloadRequest, + ListWorkloadsRequest, + ListWorkloadsResponse, + Workload, + WorkloadOnboardingState, + WorkloadOnboardingStep, +) +from .customers import ( + Customer, + CustomerOnboardingState, + CustomerOnboardingStep, + GetCustomerRequest, + ListCustomersRequest, + ListCustomersResponse, +) +from .ekm_connections import EkmConnection, EkmConnections, GetEkmConnectionsRequest +from .partner_permissions import GetPartnerPermissionsRequest, PartnerPermissions +from .partners import EkmMetadata, GetPartnerRequest, Partner, Sku +from .violations import ( + GetViolationRequest, + ListViolationsRequest, + ListViolationsResponse, + Violation, +) + +__all__ = ( + "AccessApprovalRequest", + "AccessReason", + "ListAccessApprovalRequestsRequest", + "ListAccessApprovalRequestsResponse", + "CompletionState", + "OperationMetadata", + "GetWorkloadRequest", + "ListWorkloadsRequest", + "ListWorkloadsResponse", + "Workload", + "WorkloadOnboardingState", + "WorkloadOnboardingStep", + "Customer", + "CustomerOnboardingState", + "CustomerOnboardingStep", + "GetCustomerRequest", + "ListCustomersRequest", + "ListCustomersResponse", + "EkmConnection", + "EkmConnections", + "GetEkmConnectionsRequest", + "GetPartnerPermissionsRequest", + "PartnerPermissions", + "EkmMetadata", + "GetPartnerRequest", + "Partner", + "Sku", + "GetViolationRequest", + "ListViolationsRequest", + "ListViolationsResponse", + "Violation", +) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/access_approval_requests.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/access_approval_requests.py new file mode 100644 index 000000000000..c8522e4178e1 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/access_approval_requests.py @@ -0,0 +1,230 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloudcontrolspartner.v1beta", + manifest={ + "AccessApprovalRequest", + "ListAccessApprovalRequestsRequest", + "ListAccessApprovalRequestsResponse", + "AccessReason", + }, +) + + +class AccessApprovalRequest(proto.Message): + r"""Details about the Access request. + + Attributes: + name (str): + Identifier. Format: + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/accessApprovalRequests/{access_approval_request}. + request_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which approval was requested. + requested_reason (google.cloud.cloudcontrolspartner_v1beta.types.AccessReason): + The justification for which approval is being + requested. + requested_expiration_time (google.protobuf.timestamp_pb2.Timestamp): + The requested expiration for the approval. If + the request is approved, access will be granted + from the time of approval until the expiration + time. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + requested_reason: "AccessReason" = proto.Field( + proto.MESSAGE, + number=3, + message="AccessReason", + ) + requested_expiration_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class ListAccessApprovalRequestsRequest(proto.Message): + r"""Request for getting the access requests associated with a + workload. + + Attributes: + parent (str): + Required. Parent resource + Format: + + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload} + page_size (int): + Optional. The maximum number of access + requests to return. The service may return fewer + than this value. If unspecified, at most 500 + access requests will be returned. + page_token (str): + Optional. A page token, received from a previous + ``ListAccessApprovalRequests`` call. Provide this to + retrieve the subsequent page. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + """ + + 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, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListAccessApprovalRequestsResponse(proto.Message): + r"""Response message for list access requests. + + Attributes: + access_approval_requests (MutableSequence[google.cloud.cloudcontrolspartner_v1beta.types.AccessApprovalRequest]): + List of access approval requests + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + access_approval_requests: MutableSequence[ + "AccessApprovalRequest" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AccessApprovalRequest", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class AccessReason(proto.Message): + r"""Reason for the access. + + Attributes: + type_ (google.cloud.cloudcontrolspartner_v1beta.types.AccessReason.Type): + Type of access justification. + detail (str): + More detail about certain reason types. See + comments for each type above. + """ + + class Type(proto.Enum): + r"""Type of access justification. + + Values: + TYPE_UNSPECIFIED (0): + Default value for proto, shouldn't be used. + CUSTOMER_INITIATED_SUPPORT (1): + Customer made a request or raised an issue that required the + principal to access customer data. ``detail`` is of the form + ("#####" is the issue ID): + + - "Feedback Report: #####" + - "Case Number: #####" + - "Case ID: #####" + - "E-PIN Reference: #####" + - "Google-#####" + - "T-#####". + GOOGLE_INITIATED_SERVICE (2): + The principal accessed customer data in order + to diagnose or resolve a suspected issue in + services. Often this access is used to confirm + that customers are not affected by a suspected + service issue or to remediate a reversible + system issue. + GOOGLE_INITIATED_REVIEW (3): + Google initiated service for security, fraud, + abuse, or compliance purposes. + THIRD_PARTY_DATA_REQUEST (4): + The principal was compelled to access + customer data in order to respond to a legal + third party data request or process, including + legal processes from customers themselves. + GOOGLE_RESPONSE_TO_PRODUCTION_ALERT (5): + The principal accessed customer data in order + to diagnose or resolve a suspected issue in + services or a known outage. + CLOUD_INITIATED_ACCESS (6): + Similar to 'GOOGLE_INITIATED_SERVICE' or + 'GOOGLE_INITIATED_REVIEW', but with universe agnostic + naming. The principal accessed customer data in order to + diagnose or resolve a suspected issue in services or a known + outage, or for security, fraud, abuse, or compliance review + purposes. + """ + TYPE_UNSPECIFIED = 0 + CUSTOMER_INITIATED_SUPPORT = 1 + GOOGLE_INITIATED_SERVICE = 2 + GOOGLE_INITIATED_REVIEW = 3 + THIRD_PARTY_DATA_REQUEST = 4 + GOOGLE_RESPONSE_TO_PRODUCTION_ALERT = 5 + CLOUD_INITIATED_ACCESS = 6 + + type_: Type = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + detail: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/completion_state.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/completion_state.py new file mode 100644 index 000000000000..0512582e8a00 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/completion_state.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloudcontrolspartner.v1beta", + manifest={ + "CompletionState", + }, +) + + +class CompletionState(proto.Enum): + r"""Enum for possible completion states. + + Values: + COMPLETION_STATE_UNSPECIFIED (0): + Unspecified completion state. + PENDING (1): + Task started (has start date) but not yet + completed. + SUCCEEDED (2): + Succeeded state. + FAILED (3): + Failed state. + NOT_APPLICABLE (4): + Not applicable state. + """ + COMPLETION_STATE_UNSPECIFIED = 0 + PENDING = 1 + SUCCEEDED = 2 + FAILED = 3 + NOT_APPLICABLE = 4 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/core.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/core.py new file mode 100644 index 000000000000..a5d981265c87 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/core.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloudcontrolspartner.v1beta", + manifest={ + "OperationMetadata", + }, +) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have been + cancelled successfully have [Operation.error][] value with a + [google.rpc.Status.code][google.rpc.Status.code] of 1, + corresponding to ``Code.CANCELLED``. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/customer_workloads.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/customer_workloads.py new file mode 100644 index 000000000000..097c9ac84f7a --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/customer_workloads.py @@ -0,0 +1,304 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloudcontrolspartner_v1beta.types import ( + completion_state as gcc_completion_state, +) + +__protobuf__ = proto.module( + package="google.cloud.cloudcontrolspartner.v1beta", + manifest={ + "Workload", + "ListWorkloadsRequest", + "ListWorkloadsResponse", + "GetWorkloadRequest", + "WorkloadOnboardingState", + "WorkloadOnboardingStep", + }, +) + + +class Workload(proto.Message): + r"""Contains metadata around the `Workload + resource `__ + in the Assured Workloads API. + + Attributes: + name (str): + Identifier. Format: + + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload} + folder_id (int): + Output only. Folder id this workload is + associated with + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time the resource was created. + folder (str): + Output only. The name of container folder of + the assured workload + workload_onboarding_state (google.cloud.cloudcontrolspartner_v1beta.types.WorkloadOnboardingState): + Container for workload onboarding steps. + is_onboarded (bool): + Indicates whether a workload is fully + onboarded. + key_management_project_id (str): + The project id of the key management project + for the workload + location (str): + The Google Cloud location of the workload + partner (google.cloud.cloudcontrolspartner_v1beta.types.Workload.Partner): + Partner associated with this workload. + """ + + class Partner(proto.Enum): + r"""Supported Assured Workloads Partners. + + Values: + PARTNER_UNSPECIFIED (0): + Unknown Partner. + PARTNER_LOCAL_CONTROLS_BY_S3NS (1): + Enum representing S3NS (Thales) partner. + PARTNER_SOVEREIGN_CONTROLS_BY_T_SYSTEMS (2): + Enum representing T_SYSTEM (TSI) partner. + PARTNER_SOVEREIGN_CONTROLS_BY_SIA_MINSAIT (3): + Enum representing SIA_MINSAIT (Indra) partner. + PARTNER_SOVEREIGN_CONTROLS_BY_PSN (4): + Enum representing PSN (TIM) partner. + PARTNER_SOVEREIGN_CONTROLS_BY_CNTXT (6): + Enum representing CNTXT (Kingdom of Saudi + Arabia) partner. + PARTNER_SOVEREIGN_CONTROLS_BY_CNTXT_NO_EKM (7): + Enum representing CNXT (Kingdom of Saudi + Arabia) partner offering without EKM + provisioning. + """ + PARTNER_UNSPECIFIED = 0 + PARTNER_LOCAL_CONTROLS_BY_S3NS = 1 + PARTNER_SOVEREIGN_CONTROLS_BY_T_SYSTEMS = 2 + PARTNER_SOVEREIGN_CONTROLS_BY_SIA_MINSAIT = 3 + PARTNER_SOVEREIGN_CONTROLS_BY_PSN = 4 + PARTNER_SOVEREIGN_CONTROLS_BY_CNTXT = 6 + PARTNER_SOVEREIGN_CONTROLS_BY_CNTXT_NO_EKM = 7 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + folder_id: int = proto.Field( + proto.INT64, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + folder: str = proto.Field( + proto.STRING, + number=4, + ) + workload_onboarding_state: "WorkloadOnboardingState" = proto.Field( + proto.MESSAGE, + number=5, + message="WorkloadOnboardingState", + ) + is_onboarded: bool = proto.Field( + proto.BOOL, + number=6, + ) + key_management_project_id: str = proto.Field( + proto.STRING, + number=7, + ) + location: str = proto.Field( + proto.STRING, + number=8, + ) + partner: Partner = proto.Field( + proto.ENUM, + number=9, + enum=Partner, + ) + + +class ListWorkloadsRequest(proto.Message): + r"""Request to list customer workloads. + + Attributes: + parent (str): + Required. Parent resource + Format: + + organizations/{organization}/locations/{location}/customers/{customer} + page_size (int): + The maximum number of workloads to return. + The service may return fewer than this value. If + unspecified, at most 500 workloads will be + returned. + page_token (str): + A page token, received from a previous ``ListWorkloads`` + call. Provide this to retrieve the subsequent page. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + """ + + 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, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListWorkloadsResponse(proto.Message): + r"""Response message for list customer workloads requests. + + Attributes: + workloads (MutableSequence[google.cloud.cloudcontrolspartner_v1beta.types.Workload]): + List of customer workloads + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + workloads: MutableSequence["Workload"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Workload", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetWorkloadRequest(proto.Message): + r"""Message for getting a customer workload. + + Attributes: + name (str): + Required. Format: + + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class WorkloadOnboardingState(proto.Message): + r"""Container for workload onboarding steps. + + Attributes: + onboarding_steps (MutableSequence[google.cloud.cloudcontrolspartner_v1beta.types.WorkloadOnboardingStep]): + List of workload onboarding steps. + """ + + onboarding_steps: MutableSequence["WorkloadOnboardingStep"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="WorkloadOnboardingStep", + ) + + +class WorkloadOnboardingStep(proto.Message): + r"""Container for workload onboarding information. + + Attributes: + step (google.cloud.cloudcontrolspartner_v1beta.types.WorkloadOnboardingStep.Step): + The onboarding step. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The starting time of the onboarding step. + completion_time (google.protobuf.timestamp_pb2.Timestamp): + The completion time of the onboarding step. + completion_state (google.cloud.cloudcontrolspartner_v1beta.types.CompletionState): + Output only. The completion state of the + onboarding step. + """ + + class Step(proto.Enum): + r"""Enum for possible onboarding steps. + + Values: + STEP_UNSPECIFIED (0): + Unspecified step. + EKM_PROVISIONED (1): + EKM Provisioned step. + SIGNED_ACCESS_APPROVAL_CONFIGURED (2): + Signed Access Approval step. + """ + STEP_UNSPECIFIED = 0 + EKM_PROVISIONED = 1 + SIGNED_ACCESS_APPROVAL_CONFIGURED = 2 + + step: Step = proto.Field( + proto.ENUM, + number=1, + enum=Step, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + completion_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + completion_state: gcc_completion_state.CompletionState = proto.Field( + proto.ENUM, + number=4, + enum=gcc_completion_state.CompletionState, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/customers.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/customers.py new file mode 100644 index 000000000000..8d6426e2de81 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/customers.py @@ -0,0 +1,236 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloudcontrolspartner_v1beta.types import ( + completion_state as gcc_completion_state, +) + +__protobuf__ = proto.module( + package="google.cloud.cloudcontrolspartner.v1beta", + manifest={ + "Customer", + "ListCustomersRequest", + "ListCustomersResponse", + "GetCustomerRequest", + "CustomerOnboardingState", + "CustomerOnboardingStep", + }, +) + + +class Customer(proto.Message): + r"""Contains metadata around a Cloud Controls Partner Customer + + Attributes: + name (str): + Identifier. Format: + + organizations/{organization}/locations/{location}/customers/{customer} + display_name (str): + The customer organization's display name. + E.g. "google.com". + customer_onboarding_state (google.cloud.cloudcontrolspartner_v1beta.types.CustomerOnboardingState): + Container for customer onboarding steps + is_onboarded (bool): + Indicates whether a customer is fully + onboarded + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + customer_onboarding_state: "CustomerOnboardingState" = proto.Field( + proto.MESSAGE, + number=3, + message="CustomerOnboardingState", + ) + is_onboarded: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListCustomersRequest(proto.Message): + r"""Request to list customers + + Attributes: + parent (str): + Required. Parent resource + Format: + organizations/{organization}/locations/{location} + page_size (int): + The maximum number of Customers to return. + The service may return fewer than this value. If + unspecified, at most 500 Customers will be + returned. + page_token (str): + A page token, received from a previous ``ListCustomers`` + call. Provide this to retrieve the subsequent page. + filter (str): + Optional. Filtering results + order_by (str): + Optional. Hint for how to order the results + """ + + 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, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListCustomersResponse(proto.Message): + r"""Response message for list customer Customers requests + + Attributes: + customers (MutableSequence[google.cloud.cloudcontrolspartner_v1beta.types.Customer]): + List of customers + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + customers: MutableSequence["Customer"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Customer", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetCustomerRequest(proto.Message): + r"""Message for getting a customer + + Attributes: + name (str): + Required. Format: + + organizations/{organization}/locations/{location}/customers/{customer} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CustomerOnboardingState(proto.Message): + r"""Container for customer onboarding steps + + Attributes: + onboarding_steps (MutableSequence[google.cloud.cloudcontrolspartner_v1beta.types.CustomerOnboardingStep]): + List of customer onboarding steps + """ + + onboarding_steps: MutableSequence["CustomerOnboardingStep"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="CustomerOnboardingStep", + ) + + +class CustomerOnboardingStep(proto.Message): + r"""Container for customer onboarding information + + Attributes: + step (google.cloud.cloudcontrolspartner_v1beta.types.CustomerOnboardingStep.Step): + The onboarding step + start_time (google.protobuf.timestamp_pb2.Timestamp): + The starting time of the onboarding step + completion_time (google.protobuf.timestamp_pb2.Timestamp): + The completion time of the onboarding step + completion_state (google.cloud.cloudcontrolspartner_v1beta.types.CompletionState): + Output only. Current state of the step + """ + + class Step(proto.Enum): + r"""Enum for possible onboarding steps + + Values: + STEP_UNSPECIFIED (0): + Unspecified step + KAJ_ENROLLMENT (1): + KAJ Enrollment + CUSTOMER_ENVIRONMENT (2): + Customer Environment + """ + STEP_UNSPECIFIED = 0 + KAJ_ENROLLMENT = 1 + CUSTOMER_ENVIRONMENT = 2 + + step: Step = proto.Field( + proto.ENUM, + number=1, + enum=Step, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + completion_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + completion_state: gcc_completion_state.CompletionState = proto.Field( + proto.ENUM, + number=4, + enum=gcc_completion_state.CompletionState, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/ekm_connections.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/ekm_connections.py new file mode 100644 index 000000000000..b99d6335e047 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/ekm_connections.py @@ -0,0 +1,143 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloudcontrolspartner.v1beta", + manifest={ + "EkmConnections", + "GetEkmConnectionsRequest", + "EkmConnection", + }, +) + + +class EkmConnections(proto.Message): + r"""The EKM connections associated with a workload + + Attributes: + name (str): + Identifier. Format: + + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/ekmConnections + ekm_connections (MutableSequence[google.cloud.cloudcontrolspartner_v1beta.types.EkmConnection]): + The EKM connections associated with the + workload + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ekm_connections: MutableSequence["EkmConnection"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="EkmConnection", + ) + + +class GetEkmConnectionsRequest(proto.Message): + r"""Request for getting the EKM connections associated with a + workload + + Attributes: + name (str): + Required. Format: + + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/ekmConnections + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EkmConnection(proto.Message): + r"""Details about the EKM connection + + Attributes: + connection_name (str): + Resource name of the EKM connection in the format: + projects/{project}/locations/{location}/ekmConnections/{ekm_connection} + connection_state (google.cloud.cloudcontrolspartner_v1beta.types.EkmConnection.ConnectionState): + Output only. The connection state + connection_error (google.cloud.cloudcontrolspartner_v1beta.types.EkmConnection.ConnectionError): + The connection error that occurred if any + """ + + class ConnectionState(proto.Enum): + r"""The EKM connection state. + + Values: + CONNECTION_STATE_UNSPECIFIED (0): + Unspecified EKM connection state + AVAILABLE (1): + Available EKM connection state + NOT_AVAILABLE (2): + Not available EKM connection state + ERROR (3): + Error EKM connection state + PERMISSION_DENIED (4): + Permission denied EKM connection state + """ + CONNECTION_STATE_UNSPECIFIED = 0 + AVAILABLE = 1 + NOT_AVAILABLE = 2 + ERROR = 3 + PERMISSION_DENIED = 4 + + class ConnectionError(proto.Message): + r"""Information around the error that occurred if the connection + state is anything other than available or unspecified + + Attributes: + error_domain (str): + The error domain for the error + error_message (str): + The error message for the error + """ + + error_domain: str = proto.Field( + proto.STRING, + number=1, + ) + error_message: str = proto.Field( + proto.STRING, + number=2, + ) + + connection_name: str = proto.Field( + proto.STRING, + number=1, + ) + connection_state: ConnectionState = proto.Field( + proto.ENUM, + number=2, + enum=ConnectionState, + ) + connection_error: ConnectionError = proto.Field( + proto.MESSAGE, + number=3, + message=ConnectionError, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/monitoring.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/monitoring.py new file mode 100644 index 000000000000..38de6aea753d --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/monitoring.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.cloudcontrolspartner.v1beta", + manifest={}, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/partner_permissions.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/partner_permissions.py new file mode 100644 index 000000000000..b7076538e83c --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/partner_permissions.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloudcontrolspartner.v1beta", + manifest={ + "PartnerPermissions", + "GetPartnerPermissionsRequest", + }, +) + + +class PartnerPermissions(proto.Message): + r"""The permissions granted to the partner for a workload + + Attributes: + name (str): + Identifier. Format: + + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/partnerPermissions + partner_permissions (MutableSequence[google.cloud.cloudcontrolspartner_v1beta.types.PartnerPermissions.Permission]): + The partner permissions granted for the + workload + """ + + class Permission(proto.Enum): + r""" + + Values: + PERMISSION_UNSPECIFIED (0): + Unspecified partner permission + ACCESS_TRANSPARENCY_AND_EMERGENCY_ACCESS_LOGS (1): + Permission for Access Transparency and + emergency logs + ASSURED_WORKLOADS_MONITORING (2): + Permission for Assured Workloads monitoring + violations + ACCESS_APPROVAL_REQUESTS (3): + Permission for Access Approval requests + ASSURED_WORKLOADS_EKM_CONNECTION_STATUS (4): + Permission for External Key Manager + connection status + """ + PERMISSION_UNSPECIFIED = 0 + ACCESS_TRANSPARENCY_AND_EMERGENCY_ACCESS_LOGS = 1 + ASSURED_WORKLOADS_MONITORING = 2 + ACCESS_APPROVAL_REQUESTS = 3 + ASSURED_WORKLOADS_EKM_CONNECTION_STATUS = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + partner_permissions: MutableSequence[Permission] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=Permission, + ) + + +class GetPartnerPermissionsRequest(proto.Message): + r"""Request for getting the partner permissions granted for a + workload + + Attributes: + name (str): + Required. Name of the resource to get in the + format: + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/partnerPermissions + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/partners.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/partners.py new file mode 100644 index 000000000000..601452b666ab --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/partners.py @@ -0,0 +1,189 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.cloudcontrolspartner.v1beta", + manifest={ + "Partner", + "GetPartnerRequest", + "Sku", + "EkmMetadata", + }, +) + + +class Partner(proto.Message): + r"""Message describing Partner resource + + Attributes: + name (str): + Identifier. The resource name of the partner. + Format: + organizations/{organization}/locations/{location}/partner + Example: + "organizations/123456/locations/us-central1/partner". + skus (MutableSequence[google.cloud.cloudcontrolspartner_v1beta.types.Sku]): + List of SKUs the partner is offering + ekm_solutions (MutableSequence[google.cloud.cloudcontrolspartner_v1beta.types.EkmMetadata]): + List of Google Cloud supported EKM partners + supported by the partner + operated_cloud_regions (MutableSequence[str]): + List of Google Cloud regions that the partner + sells services to customers. Valid Google Cloud + regions found here: + + https://cloud.google.com/compute/docs/regions-zones + partner_project_id (str): + Google Cloud project ID in the partner's + Google Cloud organization for receiving enhanced + Logs for Partners. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time the resource was created + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last time the resource was + updated + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + skus: MutableSequence["Sku"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="Sku", + ) + ekm_solutions: MutableSequence["EkmMetadata"] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="EkmMetadata", + ) + operated_cloud_regions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + partner_project_id: str = proto.Field( + proto.STRING, + number=7, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +class GetPartnerRequest(proto.Message): + r"""Message for getting a Partner + + Attributes: + name (str): + Required. Format: + organizations/{organization}/locations/{location}/partner + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class Sku(proto.Message): + r"""Represents the SKU a partner owns inside Google Cloud to sell + to customers. + + Attributes: + id (str): + Argentum product SKU, that is associated with + the partner offerings to customers used by + Syntro for billing purposes. SKUs can represent + resold Google products or support services. + display_name (str): + Display name of the product identified by the + SKU. A partner may want to show partner branded + names for their offerings such as local + sovereign cloud solutions. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +class EkmMetadata(proto.Message): + r"""Holds information needed by Mudbray to use partner EKMs for + workloads. + + Attributes: + ekm_solution (google.cloud.cloudcontrolspartner_v1beta.types.EkmMetadata.EkmSolution): + The Cloud EKM partner. + ekm_endpoint_uri (str): + Endpoint for sending requests to the EKM for + key provisioning during Assured Workload + creation. + """ + + class EkmSolution(proto.Enum): + r"""Represents Google Cloud supported external key management partners + `Google Cloud EKM partners + docs `__. + + Values: + EKM_SOLUTION_UNSPECIFIED (0): + Unspecified EKM solution + FORTANIX (1): + EKM Partner Fortanix + FUTUREX (2): + EKM Partner FutureX + THALES (3): + EKM Partner Thales + VIRTRU (4): + EKM Partner Virtu + """ + EKM_SOLUTION_UNSPECIFIED = 0 + FORTANIX = 1 + FUTUREX = 2 + THALES = 3 + VIRTRU = 4 + + ekm_solution: EkmSolution = proto.Field( + proto.ENUM, + number=1, + enum=EkmSolution, + ) + ekm_endpoint_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/violations.py b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/violations.py new file mode 100644 index 000000000000..b40ac6bc7978 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/google/cloud/cloudcontrolspartner_v1beta/types/violations.py @@ -0,0 +1,391 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 +from google.type import interval_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.cloudcontrolspartner.v1beta", + manifest={ + "Violation", + "ListViolationsRequest", + "ListViolationsResponse", + "GetViolationRequest", + }, +) + + +class Violation(proto.Message): + r"""Details of resource Violation + + Attributes: + name (str): + Identifier. Format: + + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/violations/{violation} + description (str): + Output only. Description for the Violation. + e.g. OrgPolicy gcp.resourceLocations has non + compliant value. + begin_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time of the event which + triggered the Violation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last time when the Violation + record was updated. + resolve_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time of the event which fixed + the Violation. If the violation is ACTIVE this + will be empty. + category (str): + Output only. Category under which this + violation is mapped. e.g. Location, Service + Usage, Access, Encryption, etc. + state (google.cloud.cloudcontrolspartner_v1beta.types.Violation.State): + Output only. State of the violation + non_compliant_org_policy (str): + Output only. Immutable. Name of the OrgPolicy which was + modified with non-compliant change and resulted this + violation. Format: + projects/{project_number}/policies/{constraint_name} + folders/{folder_id}/policies/{constraint_name} + organizations/{organization_id}/policies/{constraint_name} + folder_id (int): + The folder_id of the violation + remediation (google.cloud.cloudcontrolspartner_v1beta.types.Violation.Remediation): + Output only. Compliance violation remediation + """ + + class State(proto.Enum): + r"""Violation State Values + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + RESOLVED (1): + Violation is resolved. + UNRESOLVED (2): + Violation is Unresolved + EXCEPTION (3): + Violation is Exception + """ + STATE_UNSPECIFIED = 0 + RESOLVED = 1 + UNRESOLVED = 2 + EXCEPTION = 3 + + class Remediation(proto.Message): + r"""Represents remediation guidance to resolve compliance + violation for AssuredWorkload + + Attributes: + instructions (google.cloud.cloudcontrolspartner_v1beta.types.Violation.Remediation.Instructions): + Required. Remediation instructions to resolve + violations + compliant_values (MutableSequence[str]): + Values that can resolve the violation + For example: for list org policy violations, + this will either be the list of allowed or + denied values + remediation_type (google.cloud.cloudcontrolspartner_v1beta.types.Violation.Remediation.RemediationType): + Output only. Remediation type based on the + type of org policy values violated + """ + + class RemediationType(proto.Enum): + r"""Classifying remediation into various types based on the kind + of violation. For example, violations caused due to changes in + boolean org policy requires different remediation instructions + compared to violation caused due to changes in allowed values of + list org policy. + + Values: + REMEDIATION_TYPE_UNSPECIFIED (0): + Unspecified remediation type + REMEDIATION_BOOLEAN_ORG_POLICY_VIOLATION (1): + Remediation type for boolean org policy + REMEDIATION_LIST_ALLOWED_VALUES_ORG_POLICY_VIOLATION (2): + Remediation type for list org policy which + have allowed values in the monitoring rule + REMEDIATION_LIST_DENIED_VALUES_ORG_POLICY_VIOLATION (3): + Remediation type for list org policy which + have denied values in the monitoring rule + REMEDIATION_RESTRICT_CMEK_CRYPTO_KEY_PROJECTS_ORG_POLICY_VIOLATION (4): + Remediation type for + gcp.restrictCmekCryptoKeyProjects + REMEDIATION_RESOURCE_VIOLATION (5): + Remediation type for resource violation. + """ + REMEDIATION_TYPE_UNSPECIFIED = 0 + REMEDIATION_BOOLEAN_ORG_POLICY_VIOLATION = 1 + REMEDIATION_LIST_ALLOWED_VALUES_ORG_POLICY_VIOLATION = 2 + REMEDIATION_LIST_DENIED_VALUES_ORG_POLICY_VIOLATION = 3 + REMEDIATION_RESTRICT_CMEK_CRYPTO_KEY_PROJECTS_ORG_POLICY_VIOLATION = 4 + REMEDIATION_RESOURCE_VIOLATION = 5 + + class Instructions(proto.Message): + r"""Instructions to remediate violation + + Attributes: + gcloud_instructions (google.cloud.cloudcontrolspartner_v1beta.types.Violation.Remediation.Instructions.Gcloud): + Remediation instructions to resolve violation + via gcloud cli + console_instructions (google.cloud.cloudcontrolspartner_v1beta.types.Violation.Remediation.Instructions.Console): + Remediation instructions to resolve violation + via cloud console + """ + + class Gcloud(proto.Message): + r"""Remediation instructions to resolve violation via gcloud cli + + Attributes: + gcloud_commands (MutableSequence[str]): + Gcloud command to resolve violation + steps (MutableSequence[str]): + Steps to resolve violation via gcloud cli + additional_links (MutableSequence[str]): + Additional urls for more information about + steps + """ + + gcloud_commands: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + steps: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + additional_links: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + class Console(proto.Message): + r"""Remediation instructions to resolve violation via cloud + console + + Attributes: + console_uris (MutableSequence[str]): + Link to console page where violations can be + resolved + steps (MutableSequence[str]): + Steps to resolve violation via cloud console + additional_links (MutableSequence[str]): + Additional urls for more information about + steps + """ + + console_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + steps: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + additional_links: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + gcloud_instructions: "Violation.Remediation.Instructions.Gcloud" = ( + proto.Field( + proto.MESSAGE, + number=1, + message="Violation.Remediation.Instructions.Gcloud", + ) + ) + console_instructions: "Violation.Remediation.Instructions.Console" = ( + proto.Field( + proto.MESSAGE, + number=2, + message="Violation.Remediation.Instructions.Console", + ) + ) + + instructions: "Violation.Remediation.Instructions" = proto.Field( + proto.MESSAGE, + number=1, + message="Violation.Remediation.Instructions", + ) + compliant_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + remediation_type: "Violation.Remediation.RemediationType" = proto.Field( + proto.ENUM, + number=3, + enum="Violation.Remediation.RemediationType", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + begin_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + resolve_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + category: str = proto.Field( + proto.STRING, + number=6, + ) + state: State = proto.Field( + proto.ENUM, + number=7, + enum=State, + ) + non_compliant_org_policy: str = proto.Field( + proto.STRING, + number=8, + ) + folder_id: int = proto.Field( + proto.INT64, + number=9, + ) + remediation: Remediation = proto.Field( + proto.MESSAGE, + number=13, + message=Remediation, + ) + + +class ListViolationsRequest(proto.Message): + r"""Message for requesting list of Violations + + Attributes: + parent (str): + Required. Parent resource + Format + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload} + page_size (int): + Optional. The maximum number of customers row + to return. The service may return fewer than + this value. If unspecified, at most 10 customers + will be returned. + page_token (str): + Optional. A page token, received from a previous + ``ListViolations`` call. Provide this to retrieve the + subsequent page. + filter (str): + Optional. Filtering results + order_by (str): + Optional. Hint for how to order the results + interval (google.type.interval_pb2.Interval): + Optional. Specifies the interval for + retrieving violations. if unspecified, all + violations will be returned. + """ + + 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, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + interval: interval_pb2.Interval = proto.Field( + proto.MESSAGE, + number=6, + message=interval_pb2.Interval, + ) + + +class ListViolationsResponse(proto.Message): + r"""Response message for list customer violation requests + + Attributes: + violations (MutableSequence[google.cloud.cloudcontrolspartner_v1beta.types.Violation]): + List of violation + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Workloads that could not be reached due to + permission errors or any other error. Ref: + https://google.aip.dev/217 + """ + + @property + def raw_page(self): + return self + + violations: MutableSequence["Violation"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Violation", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetViolationRequest(proto.Message): + r"""Message for getting a Violation + + Attributes: + name (str): + Required. Format: + + organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/violations/{violation} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-cloudcontrolspartner/mypy.ini b/packages/google-cloud-cloudcontrolspartner/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/packages/google-cloud-cloudcontrolspartner/noxfile.py b/packages/google-cloud-cloudcontrolspartner/noxfile.py new file mode 100644 index 000000000000..1e6cd48d0529 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/noxfile.py @@ -0,0 +1,428 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2023 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 +# +# https://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 by synthtool. DO NOT EDIT! + +from __future__ import absolute_import + +import os +import pathlib +import re +import shutil +from typing import Dict, List +import warnings + +import nox + +BLACK_VERSION = "black[jupyter]==23.7.0" +ISORT_VERSION = "isort==5.11.0" + +LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] + + +DEFAULT_PYTHON_VERSION = "3.10" + +UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "asyncmock", + "pytest", + "pytest-cov", + "pytest-asyncio", +] +UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_DEPENDENCIES: List[str] = [] +UNIT_TEST_EXTRAS: List[str] = [] +UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "pytest", + "google-cloud-testutils", +] +SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_EXTRAS: List[str] = [] +SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +# 'docfx' is excluded since it only needs to run in 'docs-presubmit' +nox.options.sessions = [ + "unit", + "system", + "cover", + "lint", + "lint_setup_py", + "blacken", + "docs", +] + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *LINT_PATHS, + ) + + session.run("flake8", "google", "tests") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def format(session): + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run( + "isort", + "--fss", + *LINT_PATHS, + ) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") + + +def install_unittest_dependencies(session, *constraints): + standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES + session.install(*standard_deps, *constraints) + + if UNIT_TEST_EXTERNAL_DEPENDENCIES: + warnings.warn( + "'unit_test_external_dependencies' is deprecated. Instead, please " + "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", + DeprecationWarning, + ) + session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_LOCAL_DEPENDENCIES: + session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_EXTRAS_BY_PYTHON: + extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif UNIT_TEST_EXTRAS: + extras = UNIT_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +def default(session): + # Install all test dependencies, then install this package in-place. + + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + install_unittest_dependencies(session, "-c", constraints_path) + + # Run py.test against the unit tests. + session.run( + "py.test", + "--quiet", + f"--junitxml=unit_{session.python}_sponge_log.xml", + "--cov=google", + "--cov=tests/unit", + "--cov-append", + "--cov-config=.coveragerc", + "--cov-report=", + "--cov-fail-under=0", + os.path.join("tests", "unit"), + *session.posargs, + ) + + +@nox.session(python=UNIT_TEST_PYTHON_VERSIONS) +def unit(session): + """Run the unit test suite.""" + default(session) + + +def install_systemtest_dependencies(session, *constraints): + # Use pre-release gRPC for system tests. + # Exclude version 1.52.0rc1 which has a known issue. + # See https://github.com/grpc/grpc/issues/32163 + session.install("--pre", "grpcio!=1.52.0rc1") + + session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: + session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_LOCAL_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTRAS_BY_PYTHON: + extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif SYSTEM_TEST_EXTRAS: + extras = SYSTEM_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) +def system(session): + """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + system_test_path = os.path.join("tests", "system.py") + system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") + # Install pyopenssl for mTLS testing. + if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": + session.install("pyopenssl") + + system_test_exists = os.path.exists(system_test_path) + system_test_folder_exists = os.path.exists(system_test_folder_path) + # Sanity check: only run tests if found. + if not system_test_exists and not system_test_folder_exists: + session.skip("System tests were not found") + + install_systemtest_dependencies(session, "-c", constraints_path) + + # Run py.test against the system tests. + if system_test_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_path, + *session.posargs, + ) + if system_test_folder_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_folder_path, + *session.posargs, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "sphinx==4.5.0", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "gcp-sphinx-docfx-yaml", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python="3.12") +def prerelease_deps(session): + """Run all tests with prerelease versions of dependencies installed.""" + + # Install all dependencies + session.install("-e", ".[all, tests, tracing]") + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY + / "testing" + / f"constraints-{UNIT_TEST_PYTHON_VERSIONS[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "protobuf", + # dependency of grpc + "six", + "googleapis-common-protos", + # Exclude version 1.52.0rc1 which has a known issue. See https://github.com/grpc/grpc/issues/32163 + "grpcio!=1.52.0rc1", + "grpcio-status", + "google-api-core", + "google-auth", + "proto-plus", + "google-cloud-testutils", + # dependencies of google-cloud-testutils" + "click", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + + session.run("py.test", "tests/unit") diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_customer_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_customer_async.py new file mode 100644 index 000000000000..6983f3b2e7d2 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_customer_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetCustomer +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetCustomer_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 cloudcontrolspartner_v1 + + +async def sample_get_customer(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetCustomerRequest( + name="name_value", + ) + + # Make the request + response = await client.get_customer(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetCustomer_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_customer_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_customer_sync.py new file mode 100644 index 000000000000..2fa1c45f82dd --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_customer_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetCustomer +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetCustomer_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 cloudcontrolspartner_v1 + + +def sample_get_customer(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetCustomerRequest( + name="name_value", + ) + + # Make the request + response = client.get_customer(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetCustomer_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_ekm_connections_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_ekm_connections_async.py new file mode 100644 index 000000000000..e90710208918 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_ekm_connections_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetEkmConnections +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetEkmConnections_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 cloudcontrolspartner_v1 + + +async def sample_get_ekm_connections(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetEkmConnectionsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_ekm_connections(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetEkmConnections_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_ekm_connections_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_ekm_connections_sync.py new file mode 100644 index 000000000000..72d614c0b73e --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_ekm_connections_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetEkmConnections +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetEkmConnections_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 cloudcontrolspartner_v1 + + +def sample_get_ekm_connections(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetEkmConnectionsRequest( + name="name_value", + ) + + # Make the request + response = client.get_ekm_connections(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetEkmConnections_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_async.py new file mode 100644 index 000000000000..f2c81848159c --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetPartner +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetPartner_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 cloudcontrolspartner_v1 + + +async def sample_get_partner(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetPartnerRequest( + name="name_value", + ) + + # Make the request + response = await client.get_partner(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetPartner_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_permissions_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_permissions_async.py new file mode 100644 index 000000000000..11c09f27a82c --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_permissions_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetPartnerPermissions +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetPartnerPermissions_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 cloudcontrolspartner_v1 + + +async def sample_get_partner_permissions(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetPartnerPermissionsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_partner_permissions(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetPartnerPermissions_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_permissions_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_permissions_sync.py new file mode 100644 index 000000000000..dc20ab0a59b9 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_permissions_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetPartnerPermissions +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetPartnerPermissions_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 cloudcontrolspartner_v1 + + +def sample_get_partner_permissions(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetPartnerPermissionsRequest( + name="name_value", + ) + + # Make the request + response = client.get_partner_permissions(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetPartnerPermissions_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_sync.py new file mode 100644 index 000000000000..fb75f0a4463c --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetPartner +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetPartner_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 cloudcontrolspartner_v1 + + +def sample_get_partner(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetPartnerRequest( + name="name_value", + ) + + # Make the request + response = client.get_partner(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetPartner_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_workload_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_workload_async.py new file mode 100644 index 000000000000..17c4eb6bfaaf --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_workload_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetWorkload +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetWorkload_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 cloudcontrolspartner_v1 + + +async def sample_get_workload(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetWorkloadRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workload(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetWorkload_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_workload_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_workload_sync.py new file mode 100644 index 000000000000..829008f6da08 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_workload_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetWorkload +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetWorkload_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 cloudcontrolspartner_v1 + + +def sample_get_workload(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetWorkloadRequest( + name="name_value", + ) + + # Make the request + response = client.get_workload(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetWorkload_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_access_approval_requests_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_access_approval_requests_async.py new file mode 100644 index 000000000000..74a73e26ac9b --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_access_approval_requests_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListAccessApprovalRequests +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListAccessApprovalRequests_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 cloudcontrolspartner_v1 + + +async def sample_list_access_approval_requests(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.ListAccessApprovalRequestsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_access_approval_requests(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListAccessApprovalRequests_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_access_approval_requests_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_access_approval_requests_sync.py new file mode 100644 index 000000000000..d9e73dfb1be3 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_access_approval_requests_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListAccessApprovalRequests +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListAccessApprovalRequests_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 cloudcontrolspartner_v1 + + +def sample_list_access_approval_requests(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.ListAccessApprovalRequestsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_access_approval_requests(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListAccessApprovalRequests_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_customers_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_customers_async.py new file mode 100644 index 000000000000..0cf113a8b200 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_customers_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListCustomers +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListCustomers_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 cloudcontrolspartner_v1 + + +async def sample_list_customers(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.ListCustomersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_customers(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListCustomers_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_customers_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_customers_sync.py new file mode 100644 index 000000000000..62e39ba04d09 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_customers_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListCustomers +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListCustomers_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 cloudcontrolspartner_v1 + + +def sample_list_customers(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.ListCustomersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_customers(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListCustomers_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_workloads_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_workloads_async.py new file mode 100644 index 000000000000..30f5db25d2af --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_workloads_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListWorkloads +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListWorkloads_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 cloudcontrolspartner_v1 + + +async def sample_list_workloads(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.ListWorkloadsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workloads(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListWorkloads_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_workloads_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_workloads_sync.py new file mode 100644 index 000000000000..85fd1a7019bd --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_workloads_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListWorkloads +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListWorkloads_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 cloudcontrolspartner_v1 + + +def sample_list_workloads(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.ListWorkloadsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workloads(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListWorkloads_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_get_violation_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_get_violation_async.py new file mode 100644 index 000000000000..ab05d15fdd9e --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_get_violation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetViolation +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerMonitoring_GetViolation_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 cloudcontrolspartner_v1 + + +async def sample_get_violation(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerMonitoringAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetViolationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_violation(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerMonitoring_GetViolation_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_get_violation_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_get_violation_sync.py new file mode 100644 index 000000000000..321f8fe59e63 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_get_violation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetViolation +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerMonitoring_GetViolation_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 cloudcontrolspartner_v1 + + +def sample_get_violation(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerMonitoringClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.GetViolationRequest( + name="name_value", + ) + + # Make the request + response = client.get_violation(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerMonitoring_GetViolation_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_list_violations_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_list_violations_async.py new file mode 100644 index 000000000000..0e86b915a761 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_list_violations_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListViolations +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerMonitoring_ListViolations_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 cloudcontrolspartner_v1 + + +async def sample_list_violations(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerMonitoringAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.ListViolationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_violations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerMonitoring_ListViolations_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_list_violations_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_list_violations_sync.py new file mode 100644 index 000000000000..cf3296f9540c --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_list_violations_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListViolations +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1_generated_CloudControlsPartnerMonitoring_ListViolations_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 cloudcontrolspartner_v1 + + +def sample_list_violations(): + # Create a client + client = cloudcontrolspartner_v1.CloudControlsPartnerMonitoringClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1.ListViolationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_violations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudcontrolspartner_v1_generated_CloudControlsPartnerMonitoring_ListViolations_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_customer_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_customer_async.py new file mode 100644 index 000000000000..bf03bb4fde22 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_customer_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetCustomer +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetCustomer_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 cloudcontrolspartner_v1beta + + +async def sample_get_customer(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetCustomerRequest( + name="name_value", + ) + + # Make the request + response = await client.get_customer(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetCustomer_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_customer_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_customer_sync.py new file mode 100644 index 000000000000..f82776578ae9 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_customer_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetCustomer +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetCustomer_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 cloudcontrolspartner_v1beta + + +def sample_get_customer(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetCustomerRequest( + name="name_value", + ) + + # Make the request + response = client.get_customer(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetCustomer_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_ekm_connections_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_ekm_connections_async.py new file mode 100644 index 000000000000..0872db896d39 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_ekm_connections_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetEkmConnections +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetEkmConnections_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 cloudcontrolspartner_v1beta + + +async def sample_get_ekm_connections(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetEkmConnectionsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_ekm_connections(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetEkmConnections_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_ekm_connections_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_ekm_connections_sync.py new file mode 100644 index 000000000000..de7f8838e88a --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_ekm_connections_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetEkmConnections +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetEkmConnections_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 cloudcontrolspartner_v1beta + + +def sample_get_ekm_connections(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetEkmConnectionsRequest( + name="name_value", + ) + + # Make the request + response = client.get_ekm_connections(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetEkmConnections_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_async.py new file mode 100644 index 000000000000..661a5e9ec6cb --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetPartner +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetPartner_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 cloudcontrolspartner_v1beta + + +async def sample_get_partner(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetPartnerRequest( + name="name_value", + ) + + # Make the request + response = await client.get_partner(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetPartner_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_permissions_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_permissions_async.py new file mode 100644 index 000000000000..d0aea20d90bf --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_permissions_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetPartnerPermissions +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetPartnerPermissions_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 cloudcontrolspartner_v1beta + + +async def sample_get_partner_permissions(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetPartnerPermissionsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_partner_permissions(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetPartnerPermissions_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_permissions_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_permissions_sync.py new file mode 100644 index 000000000000..6a43555823e3 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_permissions_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetPartnerPermissions +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetPartnerPermissions_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 cloudcontrolspartner_v1beta + + +def sample_get_partner_permissions(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetPartnerPermissionsRequest( + name="name_value", + ) + + # Make the request + response = client.get_partner_permissions(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetPartnerPermissions_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_sync.py new file mode 100644 index 000000000000..b28b7d24a1ad --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetPartner +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetPartner_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 cloudcontrolspartner_v1beta + + +def sample_get_partner(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetPartnerRequest( + name="name_value", + ) + + # Make the request + response = client.get_partner(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetPartner_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_workload_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_workload_async.py new file mode 100644 index 000000000000..b46aa602066f --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_workload_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetWorkload +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetWorkload_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 cloudcontrolspartner_v1beta + + +async def sample_get_workload(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetWorkloadRequest( + name="name_value", + ) + + # Make the request + response = await client.get_workload(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetWorkload_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_workload_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_workload_sync.py new file mode 100644 index 000000000000..2f400f802c4b --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_workload_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetWorkload +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetWorkload_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 cloudcontrolspartner_v1beta + + +def sample_get_workload(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetWorkloadRequest( + name="name_value", + ) + + # Make the request + response = client.get_workload(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetWorkload_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_access_approval_requests_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_access_approval_requests_async.py new file mode 100644 index 000000000000..6af76c1d197c --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_access_approval_requests_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListAccessApprovalRequests +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListAccessApprovalRequests_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 cloudcontrolspartner_v1beta + + +async def sample_list_access_approval_requests(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.ListAccessApprovalRequestsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_access_approval_requests(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListAccessApprovalRequests_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_access_approval_requests_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_access_approval_requests_sync.py new file mode 100644 index 000000000000..0d762c54b076 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_access_approval_requests_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListAccessApprovalRequests +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListAccessApprovalRequests_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 cloudcontrolspartner_v1beta + + +def sample_list_access_approval_requests(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.ListAccessApprovalRequestsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_access_approval_requests(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListAccessApprovalRequests_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_customers_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_customers_async.py new file mode 100644 index 000000000000..82bcc9bd6507 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_customers_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListCustomers +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListCustomers_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 cloudcontrolspartner_v1beta + + +async def sample_list_customers(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.ListCustomersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_customers(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListCustomers_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_customers_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_customers_sync.py new file mode 100644 index 000000000000..6dcd07be92d2 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_customers_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListCustomers +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListCustomers_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 cloudcontrolspartner_v1beta + + +def sample_list_customers(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.ListCustomersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_customers(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListCustomers_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_workloads_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_workloads_async.py new file mode 100644 index 000000000000..8fe52be6db20 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_workloads_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListWorkloads +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListWorkloads_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 cloudcontrolspartner_v1beta + + +async def sample_list_workloads(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.ListWorkloadsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workloads(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListWorkloads_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_workloads_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_workloads_sync.py new file mode 100644 index 000000000000..7efa7a5fbcec --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_workloads_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListWorkloads +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListWorkloads_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 cloudcontrolspartner_v1beta + + +def sample_list_workloads(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.ListWorkloadsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_workloads(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListWorkloads_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_get_violation_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_get_violation_async.py new file mode 100644 index 000000000000..ce07065298d1 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_get_violation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetViolation +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerMonitoring_GetViolation_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 cloudcontrolspartner_v1beta + + +async def sample_get_violation(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerMonitoringAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetViolationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_violation(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerMonitoring_GetViolation_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_get_violation_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_get_violation_sync.py new file mode 100644 index 000000000000..9e790d067aec --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_get_violation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetViolation +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerMonitoring_GetViolation_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 cloudcontrolspartner_v1beta + + +def sample_get_violation(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerMonitoringClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.GetViolationRequest( + name="name_value", + ) + + # Make the request + response = client.get_violation(request=request) + + # Handle the response + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerMonitoring_GetViolation_sync] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_list_violations_async.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_list_violations_async.py new file mode 100644 index 000000000000..ae9d329a4f3a --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_list_violations_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListViolations +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerMonitoring_ListViolations_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 cloudcontrolspartner_v1beta + + +async def sample_list_violations(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerMonitoringAsyncClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.ListViolationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_violations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerMonitoring_ListViolations_async] diff --git a/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_list_violations_sync.py b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_list_violations_sync.py new file mode 100644 index 000000000000..b5e9592359d9 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_list_violations_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListViolations +# 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-cloudcontrolspartner + + +# [START cloudcontrolspartner_v1beta_generated_CloudControlsPartnerMonitoring_ListViolations_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 cloudcontrolspartner_v1beta + + +def sample_list_violations(): + # Create a client + client = cloudcontrolspartner_v1beta.CloudControlsPartnerMonitoringClient() + + # Initialize request argument(s) + request = cloudcontrolspartner_v1beta.ListViolationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_violations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudcontrolspartner_v1beta_generated_CloudControlsPartnerMonitoring_ListViolations_sync] 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 new file mode 100644 index 000000000000..5a93fc370b33 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/snippet_metadata_google.cloud.cloudcontrolspartner.v1.json @@ -0,0 +1,1625 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.cloudcontrolspartner.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-cloudcontrolspartner", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient", + "shortName": "CloudControlsPartnerCoreAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient.get_customer", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore.GetCustomer", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetCustomer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.GetCustomerRequest" + }, + { + "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.cloudcontrolspartner_v1.types.Customer", + "shortName": "get_customer" + }, + "description": "Sample for GetCustomer", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_customer_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetCustomer_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_customer_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreClient", + "shortName": "CloudControlsPartnerCoreClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreClient.get_customer", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore.GetCustomer", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetCustomer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.GetCustomerRequest" + }, + { + "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.cloudcontrolspartner_v1.types.Customer", + "shortName": "get_customer" + }, + "description": "Sample for GetCustomer", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_customer_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetCustomer_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_customer_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient", + "shortName": "CloudControlsPartnerCoreAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient.get_ekm_connections", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore.GetEkmConnections", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetEkmConnections" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.GetEkmConnectionsRequest" + }, + { + "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.cloudcontrolspartner_v1.types.EkmConnections", + "shortName": "get_ekm_connections" + }, + "description": "Sample for GetEkmConnections", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_ekm_connections_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetEkmConnections_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_ekm_connections_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreClient", + "shortName": "CloudControlsPartnerCoreClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreClient.get_ekm_connections", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore.GetEkmConnections", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetEkmConnections" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.GetEkmConnectionsRequest" + }, + { + "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.cloudcontrolspartner_v1.types.EkmConnections", + "shortName": "get_ekm_connections" + }, + "description": "Sample for GetEkmConnections", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_ekm_connections_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetEkmConnections_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_ekm_connections_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient", + "shortName": "CloudControlsPartnerCoreAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient.get_partner_permissions", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore.GetPartnerPermissions", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetPartnerPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.GetPartnerPermissionsRequest" + }, + { + "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.cloudcontrolspartner_v1.types.PartnerPermissions", + "shortName": "get_partner_permissions" + }, + "description": "Sample for GetPartnerPermissions", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetPartnerPermissions_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreClient", + "shortName": "CloudControlsPartnerCoreClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreClient.get_partner_permissions", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore.GetPartnerPermissions", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetPartnerPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.GetPartnerPermissionsRequest" + }, + { + "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.cloudcontrolspartner_v1.types.PartnerPermissions", + "shortName": "get_partner_permissions" + }, + "description": "Sample for GetPartnerPermissions", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetPartnerPermissions_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient", + "shortName": "CloudControlsPartnerCoreAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient.get_partner", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore.GetPartner", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetPartner" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.GetPartnerRequest" + }, + { + "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.cloudcontrolspartner_v1.types.Partner", + "shortName": "get_partner" + }, + "description": "Sample for GetPartner", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetPartner_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreClient", + "shortName": "CloudControlsPartnerCoreClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreClient.get_partner", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore.GetPartner", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetPartner" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.GetPartnerRequest" + }, + { + "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.cloudcontrolspartner_v1.types.Partner", + "shortName": "get_partner" + }, + "description": "Sample for GetPartner", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetPartner_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_partner_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient", + "shortName": "CloudControlsPartnerCoreAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient.get_workload", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore.GetWorkload", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetWorkload" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.GetWorkloadRequest" + }, + { + "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.cloudcontrolspartner_v1.types.Workload", + "shortName": "get_workload" + }, + "description": "Sample for GetWorkload", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_workload_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetWorkload_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_workload_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreClient", + "shortName": "CloudControlsPartnerCoreClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreClient.get_workload", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore.GetWorkload", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetWorkload" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.GetWorkloadRequest" + }, + { + "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.cloudcontrolspartner_v1.types.Workload", + "shortName": "get_workload" + }, + "description": "Sample for GetWorkload", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_workload_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_GetWorkload_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_get_workload_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient", + "shortName": "CloudControlsPartnerCoreAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient.list_access_approval_requests", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore.ListAccessApprovalRequests", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "ListAccessApprovalRequests" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.ListAccessApprovalRequestsRequest" + }, + { + "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.cloudcontrolspartner_v1.services.cloud_controls_partner_core.pagers.ListAccessApprovalRequestsAsyncPager", + "shortName": "list_access_approval_requests" + }, + "description": "Sample for ListAccessApprovalRequests", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_access_approval_requests_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListAccessApprovalRequests_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_access_approval_requests_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreClient", + "shortName": "CloudControlsPartnerCoreClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreClient.list_access_approval_requests", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore.ListAccessApprovalRequests", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "ListAccessApprovalRequests" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.ListAccessApprovalRequestsRequest" + }, + { + "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.cloudcontrolspartner_v1.services.cloud_controls_partner_core.pagers.ListAccessApprovalRequestsPager", + "shortName": "list_access_approval_requests" + }, + "description": "Sample for ListAccessApprovalRequests", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_access_approval_requests_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListAccessApprovalRequests_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_access_approval_requests_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient", + "shortName": "CloudControlsPartnerCoreAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient.list_customers", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore.ListCustomers", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "ListCustomers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.ListCustomersRequest" + }, + { + "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.cloudcontrolspartner_v1.services.cloud_controls_partner_core.pagers.ListCustomersAsyncPager", + "shortName": "list_customers" + }, + "description": "Sample for ListCustomers", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_customers_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListCustomers_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_customers_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreClient", + "shortName": "CloudControlsPartnerCoreClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreClient.list_customers", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore.ListCustomers", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "ListCustomers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.ListCustomersRequest" + }, + { + "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.cloudcontrolspartner_v1.services.cloud_controls_partner_core.pagers.ListCustomersPager", + "shortName": "list_customers" + }, + "description": "Sample for ListCustomers", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_customers_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListCustomers_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_customers_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient", + "shortName": "CloudControlsPartnerCoreAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreAsyncClient.list_workloads", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore.ListWorkloads", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "ListWorkloads" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.ListWorkloadsRequest" + }, + { + "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.cloudcontrolspartner_v1.services.cloud_controls_partner_core.pagers.ListWorkloadsAsyncPager", + "shortName": "list_workloads" + }, + "description": "Sample for ListWorkloads", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_workloads_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListWorkloads_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_workloads_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreClient", + "shortName": "CloudControlsPartnerCoreClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerCoreClient.list_workloads", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore.ListWorkloads", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "ListWorkloads" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.ListWorkloadsRequest" + }, + { + "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.cloudcontrolspartner_v1.services.cloud_controls_partner_core.pagers.ListWorkloadsPager", + "shortName": "list_workloads" + }, + "description": "Sample for ListWorkloads", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_workloads_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerCore_ListWorkloads_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_core_list_workloads_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerMonitoringAsyncClient", + "shortName": "CloudControlsPartnerMonitoringAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerMonitoringAsyncClient.get_violation", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerMonitoring.GetViolation", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerMonitoring", + "shortName": "CloudControlsPartnerMonitoring" + }, + "shortName": "GetViolation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.GetViolationRequest" + }, + { + "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.cloudcontrolspartner_v1.types.Violation", + "shortName": "get_violation" + }, + "description": "Sample for GetViolation", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_get_violation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerMonitoring_GetViolation_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_get_violation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerMonitoringClient", + "shortName": "CloudControlsPartnerMonitoringClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerMonitoringClient.get_violation", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerMonitoring.GetViolation", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerMonitoring", + "shortName": "CloudControlsPartnerMonitoring" + }, + "shortName": "GetViolation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.GetViolationRequest" + }, + { + "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.cloudcontrolspartner_v1.types.Violation", + "shortName": "get_violation" + }, + "description": "Sample for GetViolation", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_get_violation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerMonitoring_GetViolation_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_get_violation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerMonitoringAsyncClient", + "shortName": "CloudControlsPartnerMonitoringAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerMonitoringAsyncClient.list_violations", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerMonitoring.ListViolations", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerMonitoring", + "shortName": "CloudControlsPartnerMonitoring" + }, + "shortName": "ListViolations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.ListViolationsRequest" + }, + { + "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.cloudcontrolspartner_v1.services.cloud_controls_partner_monitoring.pagers.ListViolationsAsyncPager", + "shortName": "list_violations" + }, + "description": "Sample for ListViolations", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_list_violations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerMonitoring_ListViolations_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_list_violations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerMonitoringClient", + "shortName": "CloudControlsPartnerMonitoringClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1.CloudControlsPartnerMonitoringClient.list_violations", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerMonitoring.ListViolations", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1.CloudControlsPartnerMonitoring", + "shortName": "CloudControlsPartnerMonitoring" + }, + "shortName": "ListViolations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1.types.ListViolationsRequest" + }, + { + "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.cloudcontrolspartner_v1.services.cloud_controls_partner_monitoring.pagers.ListViolationsPager", + "shortName": "list_violations" + }, + "description": "Sample for ListViolations", + "file": "cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_list_violations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1_generated_CloudControlsPartnerMonitoring_ListViolations_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": "cloudcontrolspartner_v1_generated_cloud_controls_partner_monitoring_list_violations_sync.py" + } + ] +} 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 new file mode 100644 index 000000000000..642805220b5c --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/samples/generated_samples/snippet_metadata_google.cloud.cloudcontrolspartner.v1beta.json @@ -0,0 +1,1625 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.cloudcontrolspartner.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-cloud-cloudcontrolspartner", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient", + "shortName": "CloudControlsPartnerCoreAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient.get_customer", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore.GetCustomer", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetCustomer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.GetCustomerRequest" + }, + { + "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.cloudcontrolspartner_v1beta.types.Customer", + "shortName": "get_customer" + }, + "description": "Sample for GetCustomer", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_customer_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetCustomer_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_customer_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient", + "shortName": "CloudControlsPartnerCoreClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient.get_customer", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore.GetCustomer", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetCustomer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.GetCustomerRequest" + }, + { + "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.cloudcontrolspartner_v1beta.types.Customer", + "shortName": "get_customer" + }, + "description": "Sample for GetCustomer", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_customer_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetCustomer_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_customer_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient", + "shortName": "CloudControlsPartnerCoreAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient.get_ekm_connections", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore.GetEkmConnections", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetEkmConnections" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.GetEkmConnectionsRequest" + }, + { + "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.cloudcontrolspartner_v1beta.types.EkmConnections", + "shortName": "get_ekm_connections" + }, + "description": "Sample for GetEkmConnections", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_ekm_connections_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetEkmConnections_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_ekm_connections_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient", + "shortName": "CloudControlsPartnerCoreClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient.get_ekm_connections", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore.GetEkmConnections", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetEkmConnections" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.GetEkmConnectionsRequest" + }, + { + "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.cloudcontrolspartner_v1beta.types.EkmConnections", + "shortName": "get_ekm_connections" + }, + "description": "Sample for GetEkmConnections", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_ekm_connections_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetEkmConnections_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_ekm_connections_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient", + "shortName": "CloudControlsPartnerCoreAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient.get_partner_permissions", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore.GetPartnerPermissions", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetPartnerPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.GetPartnerPermissionsRequest" + }, + { + "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.cloudcontrolspartner_v1beta.types.PartnerPermissions", + "shortName": "get_partner_permissions" + }, + "description": "Sample for GetPartnerPermissions", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetPartnerPermissions_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient", + "shortName": "CloudControlsPartnerCoreClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient.get_partner_permissions", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore.GetPartnerPermissions", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetPartnerPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.GetPartnerPermissionsRequest" + }, + { + "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.cloudcontrolspartner_v1beta.types.PartnerPermissions", + "shortName": "get_partner_permissions" + }, + "description": "Sample for GetPartnerPermissions", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetPartnerPermissions_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient", + "shortName": "CloudControlsPartnerCoreAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient.get_partner", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore.GetPartner", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetPartner" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.GetPartnerRequest" + }, + { + "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.cloudcontrolspartner_v1beta.types.Partner", + "shortName": "get_partner" + }, + "description": "Sample for GetPartner", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetPartner_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient", + "shortName": "CloudControlsPartnerCoreClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient.get_partner", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore.GetPartner", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetPartner" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.GetPartnerRequest" + }, + { + "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.cloudcontrolspartner_v1beta.types.Partner", + "shortName": "get_partner" + }, + "description": "Sample for GetPartner", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetPartner_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_partner_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient", + "shortName": "CloudControlsPartnerCoreAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient.get_workload", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore.GetWorkload", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetWorkload" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.GetWorkloadRequest" + }, + { + "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.cloudcontrolspartner_v1beta.types.Workload", + "shortName": "get_workload" + }, + "description": "Sample for GetWorkload", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_workload_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetWorkload_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_workload_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient", + "shortName": "CloudControlsPartnerCoreClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient.get_workload", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore.GetWorkload", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "GetWorkload" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.GetWorkloadRequest" + }, + { + "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.cloudcontrolspartner_v1beta.types.Workload", + "shortName": "get_workload" + }, + "description": "Sample for GetWorkload", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_workload_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_GetWorkload_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_get_workload_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient", + "shortName": "CloudControlsPartnerCoreAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient.list_access_approval_requests", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore.ListAccessApprovalRequests", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "ListAccessApprovalRequests" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.ListAccessApprovalRequestsRequest" + }, + { + "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.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.pagers.ListAccessApprovalRequestsAsyncPager", + "shortName": "list_access_approval_requests" + }, + "description": "Sample for ListAccessApprovalRequests", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_access_approval_requests_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListAccessApprovalRequests_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_access_approval_requests_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient", + "shortName": "CloudControlsPartnerCoreClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient.list_access_approval_requests", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore.ListAccessApprovalRequests", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "ListAccessApprovalRequests" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.ListAccessApprovalRequestsRequest" + }, + { + "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.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.pagers.ListAccessApprovalRequestsPager", + "shortName": "list_access_approval_requests" + }, + "description": "Sample for ListAccessApprovalRequests", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_access_approval_requests_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListAccessApprovalRequests_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_access_approval_requests_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient", + "shortName": "CloudControlsPartnerCoreAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient.list_customers", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore.ListCustomers", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "ListCustomers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.ListCustomersRequest" + }, + { + "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.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.pagers.ListCustomersAsyncPager", + "shortName": "list_customers" + }, + "description": "Sample for ListCustomers", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_customers_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListCustomers_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_customers_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient", + "shortName": "CloudControlsPartnerCoreClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient.list_customers", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore.ListCustomers", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "ListCustomers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.ListCustomersRequest" + }, + { + "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.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.pagers.ListCustomersPager", + "shortName": "list_customers" + }, + "description": "Sample for ListCustomers", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_customers_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListCustomers_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_customers_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient", + "shortName": "CloudControlsPartnerCoreAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreAsyncClient.list_workloads", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore.ListWorkloads", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "ListWorkloads" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.ListWorkloadsRequest" + }, + { + "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.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.pagers.ListWorkloadsAsyncPager", + "shortName": "list_workloads" + }, + "description": "Sample for ListWorkloads", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_workloads_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListWorkloads_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_workloads_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient", + "shortName": "CloudControlsPartnerCoreClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerCoreClient.list_workloads", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore.ListWorkloads", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerCore", + "shortName": "CloudControlsPartnerCore" + }, + "shortName": "ListWorkloads" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.ListWorkloadsRequest" + }, + { + "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.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.pagers.ListWorkloadsPager", + "shortName": "list_workloads" + }, + "description": "Sample for ListWorkloads", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_workloads_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerCore_ListWorkloads_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_core_list_workloads_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerMonitoringAsyncClient", + "shortName": "CloudControlsPartnerMonitoringAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerMonitoringAsyncClient.get_violation", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerMonitoring.GetViolation", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerMonitoring", + "shortName": "CloudControlsPartnerMonitoring" + }, + "shortName": "GetViolation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.GetViolationRequest" + }, + { + "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.cloudcontrolspartner_v1beta.types.Violation", + "shortName": "get_violation" + }, + "description": "Sample for GetViolation", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_get_violation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerMonitoring_GetViolation_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_get_violation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerMonitoringClient", + "shortName": "CloudControlsPartnerMonitoringClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerMonitoringClient.get_violation", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerMonitoring.GetViolation", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerMonitoring", + "shortName": "CloudControlsPartnerMonitoring" + }, + "shortName": "GetViolation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.GetViolationRequest" + }, + { + "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.cloudcontrolspartner_v1beta.types.Violation", + "shortName": "get_violation" + }, + "description": "Sample for GetViolation", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_get_violation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerMonitoring_GetViolation_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_get_violation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerMonitoringAsyncClient", + "shortName": "CloudControlsPartnerMonitoringAsyncClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerMonitoringAsyncClient.list_violations", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerMonitoring.ListViolations", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerMonitoring", + "shortName": "CloudControlsPartnerMonitoring" + }, + "shortName": "ListViolations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.ListViolationsRequest" + }, + { + "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.cloudcontrolspartner_v1beta.services.cloud_controls_partner_monitoring.pagers.ListViolationsAsyncPager", + "shortName": "list_violations" + }, + "description": "Sample for ListViolations", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_list_violations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerMonitoring_ListViolations_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_list_violations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerMonitoringClient", + "shortName": "CloudControlsPartnerMonitoringClient" + }, + "fullName": "google.cloud.cloudcontrolspartner_v1beta.CloudControlsPartnerMonitoringClient.list_violations", + "method": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerMonitoring.ListViolations", + "service": { + "fullName": "google.cloud.cloudcontrolspartner.v1beta.CloudControlsPartnerMonitoring", + "shortName": "CloudControlsPartnerMonitoring" + }, + "shortName": "ListViolations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.cloudcontrolspartner_v1beta.types.ListViolationsRequest" + }, + { + "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.cloudcontrolspartner_v1beta.services.cloud_controls_partner_monitoring.pagers.ListViolationsPager", + "shortName": "list_violations" + }, + "description": "Sample for ListViolations", + "file": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_list_violations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudcontrolspartner_v1beta_generated_CloudControlsPartnerMonitoring_ListViolations_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": "cloudcontrolspartner_v1beta_generated_cloud_controls_partner_monitoring_list_violations_sync.py" + } + ] +} diff --git a/packages/google-cloud-cloudcontrolspartner/scripts/decrypt-secrets.sh b/packages/google-cloud-cloudcontrolspartner/scripts/decrypt-secrets.sh new file mode 100755 index 000000000000..0018b421ddf8 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/scripts/decrypt-secrets.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# Copyright 2023 Google LLC All rights reserved. +# +# 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. + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +ROOT=$( dirname "$DIR" ) + +# Work from the project root. +cd $ROOT + +# Prevent it from overriding files. +# We recommend that sample authors use their own service account files and cloud project. +# In that case, they are supposed to prepare these files by themselves. +if [[ -f "testing/test-env.sh" ]] || \ + [[ -f "testing/service-account.json" ]] || \ + [[ -f "testing/client-secrets.json" ]]; then + echo "One or more target files exist, aborting." + exit 1 +fi + +# Use SECRET_MANAGER_PROJECT if set, fallback to cloud-devrel-kokoro-resources. +PROJECT_ID="${SECRET_MANAGER_PROJECT:-cloud-devrel-kokoro-resources}" + +gcloud secrets versions access latest --secret="python-docs-samples-test-env" \ + --project="${PROJECT_ID}" \ + > testing/test-env.sh +gcloud secrets versions access latest \ + --secret="python-docs-samples-service-account" \ + --project="${PROJECT_ID}" \ + > testing/service-account.json +gcloud secrets versions access latest \ + --secret="python-docs-samples-client-secrets" \ + --project="${PROJECT_ID}" \ + > testing/client-secrets.json diff --git a/packages/google-cloud-cloudcontrolspartner/scripts/fixup_cloudcontrolspartner_v1_keywords.py b/packages/google-cloud-cloudcontrolspartner/scripts/fixup_cloudcontrolspartner_v1_keywords.py new file mode 100644 index 000000000000..fd41ec6bcdba --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/scripts/fixup_cloudcontrolspartner_v1_keywords.py @@ -0,0 +1,185 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class cloudcontrolspartnerCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'get_customer': ('name', ), + 'get_ekm_connections': ('name', ), + 'get_partner': ('name', ), + 'get_partner_permissions': ('name', ), + 'get_violation': ('name', ), + 'get_workload': ('name', ), + 'list_access_approval_requests': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_customers': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_violations': ('parent', 'page_size', 'page_token', 'filter', 'order_by', 'interval', ), + 'list_workloads': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=cloudcontrolspartnerCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the cloudcontrolspartner client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/packages/google-cloud-cloudcontrolspartner/scripts/fixup_cloudcontrolspartner_v1beta_keywords.py b/packages/google-cloud-cloudcontrolspartner/scripts/fixup_cloudcontrolspartner_v1beta_keywords.py new file mode 100644 index 000000000000..fd41ec6bcdba --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/scripts/fixup_cloudcontrolspartner_v1beta_keywords.py @@ -0,0 +1,185 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class cloudcontrolspartnerCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'get_customer': ('name', ), + 'get_ekm_connections': ('name', ), + 'get_partner': ('name', ), + 'get_partner_permissions': ('name', ), + 'get_violation': ('name', ), + 'get_workload': ('name', ), + 'list_access_approval_requests': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_customers': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_violations': ('parent', 'page_size', 'page_token', 'filter', 'order_by', 'interval', ), + 'list_workloads': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=cloudcontrolspartnerCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the cloudcontrolspartner client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/packages/google-cloud-cloudcontrolspartner/setup.py b/packages/google-cloud-cloudcontrolspartner/setup.py new file mode 100644 index 000000000000..3f6f848f5e37 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/setup.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = "google-cloud-cloudcontrolspartner" + + +description = "Google Cloud Cloudcontrolspartner API client library" + +version = None + +with open( + os.path.join(package_root, "google/cloud/cloudcontrolspartner/gapic_version.py") +) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert len(version_candidates) == 1 + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-cloudcontrolspartner" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/packages/google-cloud-cloudcontrolspartner/testing/.gitignore b/packages/google-cloud-cloudcontrolspartner/testing/.gitignore new file mode 100644 index 000000000000..b05fbd630881 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/testing/.gitignore @@ -0,0 +1,3 @@ +test-env.sh +service-account.json +client-secrets.json \ No newline at end of file diff --git a/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.10.txt b/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.11.txt b/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.12.txt b/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.7.txt b/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.7.txt new file mode 100644 index 000000000000..b8a550c73855 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.19.5 diff --git a/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.8.txt b/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.9.txt b/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-cloud-cloudcontrolspartner/tests/__init__.py b/packages/google-cloud-cloudcontrolspartner/tests/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-cloud-cloudcontrolspartner/tests/unit/__init__.py b/packages/google-cloud-cloudcontrolspartner/tests/unit/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/__init__.py b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1/__init__.py b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# 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 new file mode 100644 index 000000000000..2821533769b5 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1/test_cloud_controls_partner_core.py @@ -0,0 +1,7153 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import Iterable +import json +import math + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import json_format +from google.protobuf import timestamp_pb2 # type: ignore +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +from google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_core import ( + CloudControlsPartnerCoreAsyncClient, + CloudControlsPartnerCoreClient, + pagers, + transports, +) +from google.cloud.cloudcontrolspartner_v1.types import ( + access_approval_requests, + customer_workloads, + customers, + ekm_connections, + partner_permissions, + partners, +) + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CloudControlsPartnerCoreClient._get_default_mtls_endpoint(None) is None + assert ( + CloudControlsPartnerCoreClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + CloudControlsPartnerCoreClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + CloudControlsPartnerCoreClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + CloudControlsPartnerCoreClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + CloudControlsPartnerCoreClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert CloudControlsPartnerCoreClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert CloudControlsPartnerCoreClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert CloudControlsPartnerCoreClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + CloudControlsPartnerCoreClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert CloudControlsPartnerCoreClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert CloudControlsPartnerCoreClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert CloudControlsPartnerCoreClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + CloudControlsPartnerCoreClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert CloudControlsPartnerCoreClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert CloudControlsPartnerCoreClient._get_client_cert_source(None, False) is None + assert ( + CloudControlsPartnerCoreClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + CloudControlsPartnerCoreClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + CloudControlsPartnerCoreClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + CloudControlsPartnerCoreClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + CloudControlsPartnerCoreClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerCoreClient), +) +@mock.patch.object( + CloudControlsPartnerCoreAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerCoreAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = CloudControlsPartnerCoreClient._DEFAULT_UNIVERSE + default_endpoint = CloudControlsPartnerCoreClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = CloudControlsPartnerCoreClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + CloudControlsPartnerCoreClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + CloudControlsPartnerCoreClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == CloudControlsPartnerCoreClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + CloudControlsPartnerCoreClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + CloudControlsPartnerCoreClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == CloudControlsPartnerCoreClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + CloudControlsPartnerCoreClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == CloudControlsPartnerCoreClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + CloudControlsPartnerCoreClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + CloudControlsPartnerCoreClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + CloudControlsPartnerCoreClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + CloudControlsPartnerCoreClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + CloudControlsPartnerCoreClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + CloudControlsPartnerCoreClient._get_universe_domain(None, None) + == CloudControlsPartnerCoreClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + CloudControlsPartnerCoreClient._get_universe_domain("", None) + 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", + [ + (CloudControlsPartnerCoreClient, "grpc"), + (CloudControlsPartnerCoreAsyncClient, "grpc_asyncio"), + (CloudControlsPartnerCoreClient, "rest"), + ], +) +def test_cloud_controls_partner_core_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "cloudcontrolspartner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudcontrolspartner.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.CloudControlsPartnerCoreGrpcTransport, "grpc"), + (transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.CloudControlsPartnerCoreRestTransport, "rest"), + ], +) +def test_cloud_controls_partner_core_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (CloudControlsPartnerCoreClient, "grpc"), + (CloudControlsPartnerCoreAsyncClient, "grpc_asyncio"), + (CloudControlsPartnerCoreClient, "rest"), + ], +) +def test_cloud_controls_partner_core_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "cloudcontrolspartner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudcontrolspartner.googleapis.com" + ) + + +def test_cloud_controls_partner_core_client_get_transport_class(): + transport = CloudControlsPartnerCoreClient.get_transport_class() + available_transports = [ + transports.CloudControlsPartnerCoreGrpcTransport, + transports.CloudControlsPartnerCoreRestTransport, + ] + assert transport in available_transports + + transport = CloudControlsPartnerCoreClient.get_transport_class("grpc") + assert transport == transports.CloudControlsPartnerCoreGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreGrpcTransport, + "grpc", + ), + ( + CloudControlsPartnerCoreAsyncClient, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + CloudControlsPartnerCoreClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerCoreClient), +) +@mock.patch.object( + CloudControlsPartnerCoreAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerCoreAsyncClient), +) +def test_cloud_controls_partner_core_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object( + CloudControlsPartnerCoreClient, "get_transport_class" + ) as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object( + CloudControlsPartnerCoreClient, "get_transport_class" + ) as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreGrpcTransport, + "grpc", + "true", + ), + ( + CloudControlsPartnerCoreAsyncClient, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreGrpcTransport, + "grpc", + "false", + ), + ( + CloudControlsPartnerCoreAsyncClient, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreRestTransport, + "rest", + "true", + ), + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + CloudControlsPartnerCoreClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerCoreClient), +) +@mock.patch.object( + CloudControlsPartnerCoreAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerCoreAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_cloud_controls_partner_core_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", + [CloudControlsPartnerCoreClient, CloudControlsPartnerCoreAsyncClient], +) +@mock.patch.object( + CloudControlsPartnerCoreClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudControlsPartnerCoreClient), +) +@mock.patch.object( + CloudControlsPartnerCoreAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudControlsPartnerCoreAsyncClient), +) +def test_cloud_controls_partner_core_client_get_mtls_endpoint_and_cert_source( + client_class, +): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize( + "client_class", + [CloudControlsPartnerCoreClient, CloudControlsPartnerCoreAsyncClient], +) +@mock.patch.object( + CloudControlsPartnerCoreClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerCoreClient), +) +@mock.patch.object( + CloudControlsPartnerCoreAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerCoreAsyncClient), +) +def test_cloud_controls_partner_core_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = CloudControlsPartnerCoreClient._DEFAULT_UNIVERSE + default_endpoint = CloudControlsPartnerCoreClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = CloudControlsPartnerCoreClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreGrpcTransport, + "grpc", + ), + ( + CloudControlsPartnerCoreAsyncClient, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreRestTransport, + "rest", + ), + ], +) +def test_cloud_controls_partner_core_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + CloudControlsPartnerCoreAsyncClient, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreRestTransport, + "rest", + None, + ), + ], +) +def test_cloud_controls_partner_core_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_cloud_controls_partner_core_client_client_options_from_dict(): + with mock.patch( + "google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_core.transports.CloudControlsPartnerCoreGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = CloudControlsPartnerCoreClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + CloudControlsPartnerCoreAsyncClient, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_cloud_controls_partner_core_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudcontrolspartner.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="cloudcontrolspartner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + customer_workloads.GetWorkloadRequest, + dict, + ], +) +def test_get_workload(request_type, transport: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_workload), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customer_workloads.Workload( + name="name_value", + folder_id=936, + folder="folder_value", + is_onboarded=True, + key_management_project_id="key_management_project_id_value", + location="location_value", + partner=customer_workloads.Workload.Partner.PARTNER_LOCAL_CONTROLS_BY_S3NS, + ) + response = client.get_workload(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == customer_workloads.GetWorkloadRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, customer_workloads.Workload) + assert response.name == "name_value" + assert response.folder_id == 936 + assert response.folder == "folder_value" + assert response.is_onboarded is True + assert response.key_management_project_id == "key_management_project_id_value" + assert response.location == "location_value" + assert ( + response.partner + == customer_workloads.Workload.Partner.PARTNER_LOCAL_CONTROLS_BY_S3NS + ) + + +def test_get_workload_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_workload), "__call__") as call: + client.get_workload() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == customer_workloads.GetWorkloadRequest() + + +@pytest.mark.asyncio +async def test_get_workload_async( + transport: str = "grpc_asyncio", request_type=customer_workloads.GetWorkloadRequest +): + client = CloudControlsPartnerCoreAsyncClient( + 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_workload), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customer_workloads.Workload( + name="name_value", + folder_id=936, + folder="folder_value", + is_onboarded=True, + key_management_project_id="key_management_project_id_value", + location="location_value", + partner=customer_workloads.Workload.Partner.PARTNER_LOCAL_CONTROLS_BY_S3NS, + ) + ) + response = await client.get_workload(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == customer_workloads.GetWorkloadRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, customer_workloads.Workload) + assert response.name == "name_value" + assert response.folder_id == 936 + assert response.folder == "folder_value" + assert response.is_onboarded is True + assert response.key_management_project_id == "key_management_project_id_value" + assert response.location == "location_value" + assert ( + response.partner + == customer_workloads.Workload.Partner.PARTNER_LOCAL_CONTROLS_BY_S3NS + ) + + +@pytest.mark.asyncio +async def test_get_workload_async_from_dict(): + await test_get_workload_async(request_type=dict) + + +def test_get_workload_field_headers(): + client = CloudControlsPartnerCoreClient( + 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 = customer_workloads.GetWorkloadRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_workload), "__call__") as call: + call.return_value = customer_workloads.Workload() + client.get_workload(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_workload_field_headers_async(): + client = CloudControlsPartnerCoreAsyncClient( + 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 = customer_workloads.GetWorkloadRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_workload), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customer_workloads.Workload() + ) + await client.get_workload(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_workload_flattened(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_workload), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customer_workloads.Workload() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_workload( + 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_workload_flattened_error(): + client = CloudControlsPartnerCoreClient( + 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_workload( + customer_workloads.GetWorkloadRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_workload_flattened_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_workload), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customer_workloads.Workload() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customer_workloads.Workload() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_workload( + 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_workload_flattened_error_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_workload( + customer_workloads.GetWorkloadRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + customer_workloads.ListWorkloadsRequest, + dict, + ], +) +def test_list_workloads(request_type, transport: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_workloads), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customer_workloads.ListWorkloadsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_workloads(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == customer_workloads.ListWorkloadsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkloadsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_workloads_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_workloads), "__call__") as call: + client.list_workloads() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == customer_workloads.ListWorkloadsRequest() + + +@pytest.mark.asyncio +async def test_list_workloads_async( + transport: str = "grpc_asyncio", + request_type=customer_workloads.ListWorkloadsRequest, +): + client = CloudControlsPartnerCoreAsyncClient( + 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_workloads), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customer_workloads.ListWorkloadsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_workloads(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == customer_workloads.ListWorkloadsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkloadsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_workloads_async_from_dict(): + await test_list_workloads_async(request_type=dict) + + +def test_list_workloads_field_headers(): + client = CloudControlsPartnerCoreClient( + 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 = customer_workloads.ListWorkloadsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_workloads), "__call__") as call: + call.return_value = customer_workloads.ListWorkloadsResponse() + client.list_workloads(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_workloads_field_headers_async(): + client = CloudControlsPartnerCoreAsyncClient( + 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 = customer_workloads.ListWorkloadsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_workloads), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customer_workloads.ListWorkloadsResponse() + ) + await client.list_workloads(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_workloads_flattened(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_workloads), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customer_workloads.ListWorkloadsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workloads( + 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_workloads_flattened_error(): + client = CloudControlsPartnerCoreClient( + 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_workloads( + customer_workloads.ListWorkloadsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_workloads_flattened_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_workloads), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customer_workloads.ListWorkloadsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customer_workloads.ListWorkloadsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workloads( + 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_workloads_flattened_error_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_workloads( + customer_workloads.ListWorkloadsRequest(), + parent="parent_value", + ) + + +def test_list_workloads_pager(transport_name: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_workloads), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + next_page_token="abc", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[], + next_page_token="def", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + ], + next_page_token="ghi", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_workloads(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, customer_workloads.Workload) for i in results) + + +def test_list_workloads_pages(transport_name: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_workloads), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + next_page_token="abc", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[], + next_page_token="def", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + ], + next_page_token="ghi", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workloads(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_workloads_async_pager(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + next_page_token="abc", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[], + next_page_token="def", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + ], + next_page_token="ghi", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workloads( + 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, customer_workloads.Workload) for i in responses) + + +@pytest.mark.asyncio +async def test_list_workloads_async_pages(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + next_page_token="abc", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[], + next_page_token="def", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + ], + next_page_token="ghi", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + ), + 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_workloads(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", + [ + customers.GetCustomerRequest, + dict, + ], +) +def test_get_customer(request_type, transport: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_customer), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customers.Customer( + name="name_value", + display_name="display_name_value", + is_onboarded=True, + ) + response = client.get_customer(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == customers.GetCustomerRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, customers.Customer) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.is_onboarded is True + + +def test_get_customer_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_customer), "__call__") as call: + client.get_customer() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == customers.GetCustomerRequest() + + +@pytest.mark.asyncio +async def test_get_customer_async( + transport: str = "grpc_asyncio", request_type=customers.GetCustomerRequest +): + client = CloudControlsPartnerCoreAsyncClient( + 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_customer), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customers.Customer( + name="name_value", + display_name="display_name_value", + is_onboarded=True, + ) + ) + response = await client.get_customer(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == customers.GetCustomerRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, customers.Customer) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.is_onboarded is True + + +@pytest.mark.asyncio +async def test_get_customer_async_from_dict(): + await test_get_customer_async(request_type=dict) + + +def test_get_customer_field_headers(): + client = CloudControlsPartnerCoreClient( + 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 = customers.GetCustomerRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_customer), "__call__") as call: + call.return_value = customers.Customer() + client.get_customer(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_customer_field_headers_async(): + client = CloudControlsPartnerCoreAsyncClient( + 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 = customers.GetCustomerRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_customer), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(customers.Customer()) + await client.get_customer(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_customer_flattened(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_customer), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customers.Customer() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_customer( + 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_customer_flattened_error(): + client = CloudControlsPartnerCoreClient( + 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_customer( + customers.GetCustomerRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_customer_flattened_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_customer), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customers.Customer() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(customers.Customer()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_customer( + 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_customer_flattened_error_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_customer( + customers.GetCustomerRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + customers.ListCustomersRequest, + dict, + ], +) +def test_list_customers(request_type, transport: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_customers), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customers.ListCustomersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_customers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == customers.ListCustomersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_customers_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_customers), "__call__") as call: + client.list_customers() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == customers.ListCustomersRequest() + + +@pytest.mark.asyncio +async def test_list_customers_async( + transport: str = "grpc_asyncio", request_type=customers.ListCustomersRequest +): + client = CloudControlsPartnerCoreAsyncClient( + 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_customers), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customers.ListCustomersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_customers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == customers.ListCustomersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomersAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_customers_async_from_dict(): + await test_list_customers_async(request_type=dict) + + +def test_list_customers_field_headers(): + client = CloudControlsPartnerCoreClient( + 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 = customers.ListCustomersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_customers), "__call__") as call: + call.return_value = customers.ListCustomersResponse() + client.list_customers(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_customers_field_headers_async(): + client = CloudControlsPartnerCoreAsyncClient( + 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 = customers.ListCustomersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_customers), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customers.ListCustomersResponse() + ) + await client.list_customers(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_customers_flattened(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_customers), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customers.ListCustomersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_customers( + 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_customers_flattened_error(): + client = CloudControlsPartnerCoreClient( + 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_customers( + customers.ListCustomersRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_customers_flattened_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_customers), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customers.ListCustomersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customers.ListCustomersResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_customers( + 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_customers_flattened_error_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_customers( + customers.ListCustomersRequest(), + parent="parent_value", + ) + + +def test_list_customers_pager(transport_name: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_customers), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + customers.Customer(), + ], + next_page_token="abc", + ), + customers.ListCustomersResponse( + customers=[], + next_page_token="def", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + ], + next_page_token="ghi", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_customers(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, customers.Customer) for i in results) + + +def test_list_customers_pages(transport_name: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_customers), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + customers.Customer(), + ], + next_page_token="abc", + ), + customers.ListCustomersResponse( + customers=[], + next_page_token="def", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + ], + next_page_token="ghi", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + ], + ), + RuntimeError, + ) + pages = list(client.list_customers(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_customers_async_pager(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_customers), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + customers.Customer(), + ], + next_page_token="abc", + ), + customers.ListCustomersResponse( + customers=[], + next_page_token="def", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + ], + next_page_token="ghi", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_customers( + 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, customers.Customer) for i in responses) + + +@pytest.mark.asyncio +async def test_list_customers_async_pages(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_customers), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + customers.Customer(), + ], + next_page_token="abc", + ), + customers.ListCustomersResponse( + customers=[], + next_page_token="def", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + ], + next_page_token="ghi", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + ], + ), + 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_customers(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", + [ + ekm_connections.GetEkmConnectionsRequest, + dict, + ], +) +def test_get_ekm_connections(request_type, transport: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_ekm_connections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_connections.EkmConnections( + name="name_value", + ) + response = client.get_ekm_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] == ekm_connections.GetEkmConnectionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_connections.EkmConnections) + assert response.name == "name_value" + + +def test_get_ekm_connections_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connections), "__call__" + ) as call: + client.get_ekm_connections() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_connections.GetEkmConnectionsRequest() + + +@pytest.mark.asyncio +async def test_get_ekm_connections_async( + transport: str = "grpc_asyncio", + request_type=ekm_connections.GetEkmConnectionsRequest, +): + client = CloudControlsPartnerCoreAsyncClient( + 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_ekm_connections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_connections.EkmConnections( + name="name_value", + ) + ) + response = await client.get_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_connections.GetEkmConnectionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_connections.EkmConnections) + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_get_ekm_connections_async_from_dict(): + await test_get_ekm_connections_async(request_type=dict) + + +def test_get_ekm_connections_field_headers(): + client = CloudControlsPartnerCoreClient( + 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 = ekm_connections.GetEkmConnectionsRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connections), "__call__" + ) as call: + call.return_value = ekm_connections.EkmConnections() + client.get_ekm_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 + + # 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_ekm_connections_field_headers_async(): + client = CloudControlsPartnerCoreAsyncClient( + 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 = ekm_connections.GetEkmConnectionsRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connections), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_connections.EkmConnections() + ) + await client.get_ekm_connections(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_ekm_connections_flattened(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_connections.EkmConnections() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_ekm_connections( + 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_ekm_connections_flattened_error(): + client = CloudControlsPartnerCoreClient( + 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_ekm_connections( + ekm_connections.GetEkmConnectionsRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_ekm_connections_flattened_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_connections.EkmConnections() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_connections.EkmConnections() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_ekm_connections( + 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_ekm_connections_flattened_error_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_ekm_connections( + ekm_connections.GetEkmConnectionsRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + partner_permissions.GetPartnerPermissionsRequest, + dict, + ], +) +def test_get_partner_permissions(request_type, transport: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_partner_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = partner_permissions.PartnerPermissions( + name="name_value", + partner_permissions=[ + partner_permissions.PartnerPermissions.Permission.ACCESS_TRANSPARENCY_AND_EMERGENCY_ACCESS_LOGS + ], + ) + response = client.get_partner_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == partner_permissions.GetPartnerPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, partner_permissions.PartnerPermissions) + assert response.name == "name_value" + assert response.partner_permissions == [ + partner_permissions.PartnerPermissions.Permission.ACCESS_TRANSPARENCY_AND_EMERGENCY_ACCESS_LOGS + ] + + +def test_get_partner_permissions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_partner_permissions), "__call__" + ) as call: + client.get_partner_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == partner_permissions.GetPartnerPermissionsRequest() + + +@pytest.mark.asyncio +async def test_get_partner_permissions_async( + transport: str = "grpc_asyncio", + request_type=partner_permissions.GetPartnerPermissionsRequest, +): + client = CloudControlsPartnerCoreAsyncClient( + 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_partner_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + partner_permissions.PartnerPermissions( + name="name_value", + partner_permissions=[ + partner_permissions.PartnerPermissions.Permission.ACCESS_TRANSPARENCY_AND_EMERGENCY_ACCESS_LOGS + ], + ) + ) + response = await client.get_partner_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == partner_permissions.GetPartnerPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, partner_permissions.PartnerPermissions) + assert response.name == "name_value" + assert response.partner_permissions == [ + partner_permissions.PartnerPermissions.Permission.ACCESS_TRANSPARENCY_AND_EMERGENCY_ACCESS_LOGS + ] + + +@pytest.mark.asyncio +async def test_get_partner_permissions_async_from_dict(): + await test_get_partner_permissions_async(request_type=dict) + + +def test_get_partner_permissions_field_headers(): + client = CloudControlsPartnerCoreClient( + 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 = partner_permissions.GetPartnerPermissionsRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_partner_permissions), "__call__" + ) as call: + call.return_value = partner_permissions.PartnerPermissions() + client.get_partner_permissions(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_partner_permissions_field_headers_async(): + client = CloudControlsPartnerCoreAsyncClient( + 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 = partner_permissions.GetPartnerPermissionsRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_partner_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + partner_permissions.PartnerPermissions() + ) + await client.get_partner_permissions(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_partner_permissions_flattened(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_partner_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = partner_permissions.PartnerPermissions() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_partner_permissions( + 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_partner_permissions_flattened_error(): + client = CloudControlsPartnerCoreClient( + 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_partner_permissions( + partner_permissions.GetPartnerPermissionsRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_partner_permissions_flattened_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_partner_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = partner_permissions.PartnerPermissions() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + partner_permissions.PartnerPermissions() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_partner_permissions( + 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_partner_permissions_flattened_error_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_partner_permissions( + partner_permissions.GetPartnerPermissionsRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + access_approval_requests.ListAccessApprovalRequestsRequest, + dict, + ], +) +def test_list_access_approval_requests(request_type, transport: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_access_approval_requests), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = access_approval_requests.ListAccessApprovalRequestsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_access_approval_requests(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == access_approval_requests.ListAccessApprovalRequestsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccessApprovalRequestsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_access_approval_requests_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_approval_requests), "__call__" + ) as call: + client.list_access_approval_requests() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == access_approval_requests.ListAccessApprovalRequestsRequest() + + +@pytest.mark.asyncio +async def test_list_access_approval_requests_async( + transport: str = "grpc_asyncio", + request_type=access_approval_requests.ListAccessApprovalRequestsRequest, +): + client = CloudControlsPartnerCoreAsyncClient( + 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_access_approval_requests), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + access_approval_requests.ListAccessApprovalRequestsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_access_approval_requests(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == access_approval_requests.ListAccessApprovalRequestsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccessApprovalRequestsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_access_approval_requests_async_from_dict(): + await test_list_access_approval_requests_async(request_type=dict) + + +def test_list_access_approval_requests_field_headers(): + client = CloudControlsPartnerCoreClient( + 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 = access_approval_requests.ListAccessApprovalRequestsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_approval_requests), "__call__" + ) as call: + call.return_value = ( + access_approval_requests.ListAccessApprovalRequestsResponse() + ) + client.list_access_approval_requests(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_access_approval_requests_field_headers_async(): + client = CloudControlsPartnerCoreAsyncClient( + 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 = access_approval_requests.ListAccessApprovalRequestsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_approval_requests), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + access_approval_requests.ListAccessApprovalRequestsResponse() + ) + await client.list_access_approval_requests(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_access_approval_requests_flattened(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_approval_requests), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + access_approval_requests.ListAccessApprovalRequestsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_access_approval_requests( + 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_access_approval_requests_flattened_error(): + client = CloudControlsPartnerCoreClient( + 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_access_approval_requests( + access_approval_requests.ListAccessApprovalRequestsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_access_approval_requests_flattened_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_approval_requests), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + access_approval_requests.ListAccessApprovalRequestsResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + access_approval_requests.ListAccessApprovalRequestsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_access_approval_requests( + 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_access_approval_requests_flattened_error_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_access_approval_requests( + access_approval_requests.ListAccessApprovalRequestsRequest(), + parent="parent_value", + ) + + +def test_list_access_approval_requests_pager(transport_name: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_access_approval_requests), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="abc", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[], + next_page_token="def", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="ghi", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_access_approval_requests(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, access_approval_requests.AccessApprovalRequest) + for i in results + ) + + +def test_list_access_approval_requests_pages(transport_name: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_access_approval_requests), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="abc", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[], + next_page_token="def", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="ghi", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + ), + RuntimeError, + ) + pages = list(client.list_access_approval_requests(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_access_approval_requests_async_pager(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_approval_requests), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="abc", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[], + next_page_token="def", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="ghi", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_access_approval_requests( + 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, access_approval_requests.AccessApprovalRequest) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_access_approval_requests_async_pages(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_approval_requests), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="abc", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[], + next_page_token="def", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="ghi", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + ), + 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_access_approval_requests(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", + [ + partners.GetPartnerRequest, + dict, + ], +) +def test_get_partner(request_type, transport: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_partner), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = partners.Partner( + name="name_value", + operated_cloud_regions=["operated_cloud_regions_value"], + partner_project_id="partner_project_id_value", + ) + response = client.get_partner(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == partners.GetPartnerRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, partners.Partner) + assert response.name == "name_value" + assert response.operated_cloud_regions == ["operated_cloud_regions_value"] + assert response.partner_project_id == "partner_project_id_value" + + +def test_get_partner_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_partner), "__call__") as call: + client.get_partner() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == partners.GetPartnerRequest() + + +@pytest.mark.asyncio +async def test_get_partner_async( + transport: str = "grpc_asyncio", request_type=partners.GetPartnerRequest +): + client = CloudControlsPartnerCoreAsyncClient( + 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_partner), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + partners.Partner( + name="name_value", + operated_cloud_regions=["operated_cloud_regions_value"], + partner_project_id="partner_project_id_value", + ) + ) + response = await client.get_partner(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == partners.GetPartnerRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, partners.Partner) + assert response.name == "name_value" + assert response.operated_cloud_regions == ["operated_cloud_regions_value"] + assert response.partner_project_id == "partner_project_id_value" + + +@pytest.mark.asyncio +async def test_get_partner_async_from_dict(): + await test_get_partner_async(request_type=dict) + + +def test_get_partner_field_headers(): + client = CloudControlsPartnerCoreClient( + 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 = partners.GetPartnerRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_partner), "__call__") as call: + call.return_value = partners.Partner() + client.get_partner(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_partner_field_headers_async(): + client = CloudControlsPartnerCoreAsyncClient( + 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 = partners.GetPartnerRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_partner), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(partners.Partner()) + await client.get_partner(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_partner_flattened(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_partner), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = partners.Partner() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_partner( + 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_partner_flattened_error(): + client = CloudControlsPartnerCoreClient( + 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_partner( + partners.GetPartnerRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_partner_flattened_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_partner), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = partners.Partner() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(partners.Partner()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_partner( + 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_partner_flattened_error_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_partner( + partners.GetPartnerRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + customer_workloads.GetWorkloadRequest, + dict, + ], +) +def test_get_workload_rest(request_type): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/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 = customer_workloads.Workload( + name="name_value", + folder_id=936, + folder="folder_value", + is_onboarded=True, + key_management_project_id="key_management_project_id_value", + location="location_value", + partner=customer_workloads.Workload.Partner.PARTNER_LOCAL_CONTROLS_BY_S3NS, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = customer_workloads.Workload.pb(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_workload(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, customer_workloads.Workload) + assert response.name == "name_value" + assert response.folder_id == 936 + assert response.folder == "folder_value" + assert response.is_onboarded is True + assert response.key_management_project_id == "key_management_project_id_value" + assert response.location == "location_value" + assert ( + response.partner + == customer_workloads.Workload.Partner.PARTNER_LOCAL_CONTROLS_BY_S3NS + ) + + +def test_get_workload_rest_required_fields( + request_type=customer_workloads.GetWorkloadRequest, +): + transport_class = transports.CloudControlsPartnerCoreRestTransport + + 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_workload._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_workload._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 = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = customer_workloads.Workload() + # 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 = customer_workloads.Workload.pb(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_workload(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_workload_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_workload._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_workload_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerCoreRestInterceptor(), + ) + client = CloudControlsPartnerCoreClient(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.CloudControlsPartnerCoreRestInterceptor, "post_get_workload" + ) as post, mock.patch.object( + transports.CloudControlsPartnerCoreRestInterceptor, "pre_get_workload" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = customer_workloads.GetWorkloadRequest.pb( + customer_workloads.GetWorkloadRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = customer_workloads.Workload.to_json( + customer_workloads.Workload() + ) + + request = customer_workloads.GetWorkloadRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = customer_workloads.Workload() + + client.get_workload( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_workload_rest_bad_request( + transport: str = "rest", request_type=customer_workloads.GetWorkloadRequest +): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_workload(request) + + +def test_get_workload_rest_flattened(): + client = CloudControlsPartnerCoreClient( + 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 = customer_workloads.Workload() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4" + } + + # 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 = customer_workloads.Workload.pb(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_workload(**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=organizations/*/locations/*/customers/*/workloads/*}" + % client.transport._host, + args[1], + ) + + +def test_get_workload_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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_workload( + customer_workloads.GetWorkloadRequest(), + name="name_value", + ) + + +def test_get_workload_rest_error(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + customer_workloads.ListWorkloadsRequest, + dict, + ], +) +def test_list_workloads_rest(request_type): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "organizations/sample1/locations/sample2/customers/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 = customer_workloads.ListWorkloadsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = customer_workloads.ListWorkloadsResponse.pb(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_workloads(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkloadsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_workloads_rest_required_fields( + request_type=customer_workloads.ListWorkloadsRequest, +): + transport_class = transports.CloudControlsPartnerCoreRestTransport + + 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_workloads._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_workloads._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 = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = customer_workloads.ListWorkloadsResponse() + # 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 = customer_workloads.ListWorkloadsResponse.pb(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_workloads(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_workloads_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_workloads._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workloads_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerCoreRestInterceptor(), + ) + client = CloudControlsPartnerCoreClient(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.CloudControlsPartnerCoreRestInterceptor, "post_list_workloads" + ) as post, mock.patch.object( + transports.CloudControlsPartnerCoreRestInterceptor, "pre_list_workloads" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = customer_workloads.ListWorkloadsRequest.pb( + customer_workloads.ListWorkloadsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = customer_workloads.ListWorkloadsResponse.to_json( + customer_workloads.ListWorkloadsResponse() + ) + + request = customer_workloads.ListWorkloadsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = customer_workloads.ListWorkloadsResponse() + + client.list_workloads( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_workloads_rest_bad_request( + transport: str = "rest", request_type=customer_workloads.ListWorkloadsRequest +): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "organizations/sample1/locations/sample2/customers/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_workloads(request) + + +def test_list_workloads_rest_flattened(): + client = CloudControlsPartnerCoreClient( + 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 = customer_workloads.ListWorkloadsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "organizations/sample1/locations/sample2/customers/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 = customer_workloads.ListWorkloadsResponse.pb(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_workloads(**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=organizations/*/locations/*/customers/*}/workloads" + % client.transport._host, + args[1], + ) + + +def test_list_workloads_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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_workloads( + customer_workloads.ListWorkloadsRequest(), + parent="parent_value", + ) + + +def test_list_workloads_rest_pager(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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 = ( + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + next_page_token="abc", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[], + next_page_token="def", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + ], + next_page_token="ghi", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + customer_workloads.ListWorkloadsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "organizations/sample1/locations/sample2/customers/sample3" + } + + pager = client.list_workloads(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, customer_workloads.Workload) for i in results) + + pages = list(client.list_workloads(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + customers.GetCustomerRequest, + dict, + ], +) +def test_get_customer_rest(request_type): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/locations/sample2/customers/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 = customers.Customer( + name="name_value", + display_name="display_name_value", + is_onboarded=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = customers.Customer.pb(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_customer(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, customers.Customer) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.is_onboarded is True + + +def test_get_customer_rest_required_fields(request_type=customers.GetCustomerRequest): + transport_class = transports.CloudControlsPartnerCoreRestTransport + + 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_customer._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_customer._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 = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = customers.Customer() + # 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 = customers.Customer.pb(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_customer(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_customer_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_customer._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_customer_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerCoreRestInterceptor(), + ) + client = CloudControlsPartnerCoreClient(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.CloudControlsPartnerCoreRestInterceptor, "post_get_customer" + ) as post, mock.patch.object( + transports.CloudControlsPartnerCoreRestInterceptor, "pre_get_customer" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = customers.GetCustomerRequest.pb(customers.GetCustomerRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = customers.Customer.to_json(customers.Customer()) + + request = customers.GetCustomerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = customers.Customer() + + client.get_customer( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_customer_rest_bad_request( + transport: str = "rest", request_type=customers.GetCustomerRequest +): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/locations/sample2/customers/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_customer(request) + + +def test_get_customer_rest_flattened(): + client = CloudControlsPartnerCoreClient( + 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 = customers.Customer() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/customers/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 = customers.Customer.pb(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_customer(**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=organizations/*/locations/*/customers/*}" + % client.transport._host, + args[1], + ) + + +def test_get_customer_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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_customer( + customers.GetCustomerRequest(), + name="name_value", + ) + + +def test_get_customer_rest_error(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + customers.ListCustomersRequest, + dict, + ], +) +def test_list_customers_rest(request_type): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = customers.ListCustomersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = customers.ListCustomersResponse.pb(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_customers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_customers_rest_required_fields( + request_type=customers.ListCustomersRequest, +): + transport_class = transports.CloudControlsPartnerCoreRestTransport + + 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_customers._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_customers._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 = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = customers.ListCustomersResponse() + # 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 = customers.ListCustomersResponse.pb(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_customers(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_customers_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_customers._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_customers_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerCoreRestInterceptor(), + ) + client = CloudControlsPartnerCoreClient(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.CloudControlsPartnerCoreRestInterceptor, "post_list_customers" + ) as post, mock.patch.object( + transports.CloudControlsPartnerCoreRestInterceptor, "pre_list_customers" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = customers.ListCustomersRequest.pb(customers.ListCustomersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = customers.ListCustomersResponse.to_json( + customers.ListCustomersResponse() + ) + + request = customers.ListCustomersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = customers.ListCustomersResponse() + + client.list_customers( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_customers_rest_bad_request( + transport: str = "rest", request_type=customers.ListCustomersRequest +): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_customers(request) + + +def test_list_customers_rest_flattened(): + client = CloudControlsPartnerCoreClient( + 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 = customers.ListCustomersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/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 = customers.ListCustomersResponse.pb(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_customers(**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=organizations/*/locations/*}/customers" + % client.transport._host, + args[1], + ) + + +def test_list_customers_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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_customers( + customers.ListCustomersRequest(), + parent="parent_value", + ) + + +def test_list_customers_rest_pager(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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 = ( + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + customers.Customer(), + ], + next_page_token="abc", + ), + customers.ListCustomersResponse( + customers=[], + next_page_token="def", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + ], + next_page_token="ghi", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(customers.ListCustomersResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "organizations/sample1/locations/sample2"} + + pager = client.list_customers(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, customers.Customer) for i in results) + + pages = list(client.list_customers(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + ekm_connections.GetEkmConnectionsRequest, + dict, + ], +) +def test_get_ekm_connections_rest(request_type): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/ekmConnections" + } + 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 = ekm_connections.EkmConnections( + 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 = ekm_connections.EkmConnections.pb(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_ekm_connections(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_connections.EkmConnections) + assert response.name == "name_value" + + +def test_get_ekm_connections_rest_required_fields( + request_type=ekm_connections.GetEkmConnectionsRequest, +): + transport_class = transports.CloudControlsPartnerCoreRestTransport + + 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_ekm_connections._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_ekm_connections._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 = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ekm_connections.EkmConnections() + # 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 = ekm_connections.EkmConnections.pb(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_ekm_connections(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_ekm_connections_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_ekm_connections._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_ekm_connections_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerCoreRestInterceptor(), + ) + client = CloudControlsPartnerCoreClient(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.CloudControlsPartnerCoreRestInterceptor, "post_get_ekm_connections" + ) as post, mock.patch.object( + transports.CloudControlsPartnerCoreRestInterceptor, "pre_get_ekm_connections" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ekm_connections.GetEkmConnectionsRequest.pb( + ekm_connections.GetEkmConnectionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ekm_connections.EkmConnections.to_json( + ekm_connections.EkmConnections() + ) + + request = ekm_connections.GetEkmConnectionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ekm_connections.EkmConnections() + + client.get_ekm_connections( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_ekm_connections_rest_bad_request( + transport: str = "rest", request_type=ekm_connections.GetEkmConnectionsRequest +): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/ekmConnections" + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_ekm_connections(request) + + +def test_get_ekm_connections_rest_flattened(): + client = CloudControlsPartnerCoreClient( + 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 = ekm_connections.EkmConnections() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/ekmConnections" + } + + # 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 = ekm_connections.EkmConnections.pb(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_ekm_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/{name=organizations/*/locations/*/customers/*/workloads/*/ekmConnections}" + % client.transport._host, + args[1], + ) + + +def test_get_ekm_connections_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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_ekm_connections( + ekm_connections.GetEkmConnectionsRequest(), + name="name_value", + ) + + +def test_get_ekm_connections_rest_error(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + partner_permissions.GetPartnerPermissionsRequest, + dict, + ], +) +def test_get_partner_permissions_rest(request_type): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/partnerPermissions" + } + 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 = partner_permissions.PartnerPermissions( + name="name_value", + partner_permissions=[ + partner_permissions.PartnerPermissions.Permission.ACCESS_TRANSPARENCY_AND_EMERGENCY_ACCESS_LOGS + ], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = partner_permissions.PartnerPermissions.pb(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_partner_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, partner_permissions.PartnerPermissions) + assert response.name == "name_value" + assert response.partner_permissions == [ + partner_permissions.PartnerPermissions.Permission.ACCESS_TRANSPARENCY_AND_EMERGENCY_ACCESS_LOGS + ] + + +def test_get_partner_permissions_rest_required_fields( + request_type=partner_permissions.GetPartnerPermissionsRequest, +): + transport_class = transports.CloudControlsPartnerCoreRestTransport + + 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_partner_permissions._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_partner_permissions._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 = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = partner_permissions.PartnerPermissions() + # 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 = partner_permissions.PartnerPermissions.pb(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_partner_permissions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_partner_permissions_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_partner_permissions._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_partner_permissions_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerCoreRestInterceptor(), + ) + client = CloudControlsPartnerCoreClient(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.CloudControlsPartnerCoreRestInterceptor, + "post_get_partner_permissions", + ) as post, mock.patch.object( + transports.CloudControlsPartnerCoreRestInterceptor, + "pre_get_partner_permissions", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = partner_permissions.GetPartnerPermissionsRequest.pb( + partner_permissions.GetPartnerPermissionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = partner_permissions.PartnerPermissions.to_json( + partner_permissions.PartnerPermissions() + ) + + request = partner_permissions.GetPartnerPermissionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = partner_permissions.PartnerPermissions() + + client.get_partner_permissions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_partner_permissions_rest_bad_request( + transport: str = "rest", + request_type=partner_permissions.GetPartnerPermissionsRequest, +): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/partnerPermissions" + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_partner_permissions(request) + + +def test_get_partner_permissions_rest_flattened(): + client = CloudControlsPartnerCoreClient( + 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 = partner_permissions.PartnerPermissions() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/partnerPermissions" + } + + # 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 = partner_permissions.PartnerPermissions.pb(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_partner_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=organizations/*/locations/*/customers/*/workloads/*/partnerPermissions}" + % client.transport._host, + args[1], + ) + + +def test_get_partner_permissions_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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_partner_permissions( + partner_permissions.GetPartnerPermissionsRequest(), + name="name_value", + ) + + +def test_get_partner_permissions_rest_error(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + access_approval_requests.ListAccessApprovalRequestsRequest, + dict, + ], +) +def test_list_access_approval_requests_rest(request_type): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "organizations/sample1/locations/sample2/customers/sample3/workloads/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 = access_approval_requests.ListAccessApprovalRequestsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = access_approval_requests.ListAccessApprovalRequestsResponse.pb( + 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_access_approval_requests(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccessApprovalRequestsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_access_approval_requests_rest_required_fields( + request_type=access_approval_requests.ListAccessApprovalRequestsRequest, +): + transport_class = transports.CloudControlsPartnerCoreRestTransport + + 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_access_approval_requests._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_access_approval_requests._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 = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = access_approval_requests.ListAccessApprovalRequestsResponse() + # 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 = ( + access_approval_requests.ListAccessApprovalRequestsResponse.pb( + 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_access_approval_requests(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_access_approval_requests_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_access_approval_requests._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_access_approval_requests_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerCoreRestInterceptor(), + ) + client = CloudControlsPartnerCoreClient(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.CloudControlsPartnerCoreRestInterceptor, + "post_list_access_approval_requests", + ) as post, mock.patch.object( + transports.CloudControlsPartnerCoreRestInterceptor, + "pre_list_access_approval_requests", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = access_approval_requests.ListAccessApprovalRequestsRequest.pb( + access_approval_requests.ListAccessApprovalRequestsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + access_approval_requests.ListAccessApprovalRequestsResponse.to_json( + access_approval_requests.ListAccessApprovalRequestsResponse() + ) + ) + + request = access_approval_requests.ListAccessApprovalRequestsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + access_approval_requests.ListAccessApprovalRequestsResponse() + ) + + client.list_access_approval_requests( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_access_approval_requests_rest_bad_request( + transport: str = "rest", + request_type=access_approval_requests.ListAccessApprovalRequestsRequest, +): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "organizations/sample1/locations/sample2/customers/sample3/workloads/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_access_approval_requests(request) + + +def test_list_access_approval_requests_rest_flattened(): + client = CloudControlsPartnerCoreClient( + 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 = access_approval_requests.ListAccessApprovalRequestsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4" + } + + # 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 = access_approval_requests.ListAccessApprovalRequestsResponse.pb( + 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_access_approval_requests(**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=organizations/*/locations/*/customers/*/workloads/*}/accessApprovalRequests" + % client.transport._host, + args[1], + ) + + +def test_list_access_approval_requests_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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_access_approval_requests( + access_approval_requests.ListAccessApprovalRequestsRequest(), + parent="parent_value", + ) + + +def test_list_access_approval_requests_rest_pager(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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 = ( + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="abc", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[], + next_page_token="def", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="ghi", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + access_approval_requests.ListAccessApprovalRequestsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4" + } + + pager = client.list_access_approval_requests(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, access_approval_requests.AccessApprovalRequest) + for i in results + ) + + pages = list(client.list_access_approval_requests(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + partners.GetPartnerRequest, + dict, + ], +) +def test_get_partner_rest(request_type): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/locations/sample2/partner"} + 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 = partners.Partner( + name="name_value", + operated_cloud_regions=["operated_cloud_regions_value"], + partner_project_id="partner_project_id_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 = partners.Partner.pb(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_partner(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, partners.Partner) + assert response.name == "name_value" + assert response.operated_cloud_regions == ["operated_cloud_regions_value"] + assert response.partner_project_id == "partner_project_id_value" + + +def test_get_partner_rest_required_fields(request_type=partners.GetPartnerRequest): + transport_class = transports.CloudControlsPartnerCoreRestTransport + + 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_partner._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_partner._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 = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = partners.Partner() + # 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 = partners.Partner.pb(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_partner(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_partner_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_partner._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_partner_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerCoreRestInterceptor(), + ) + client = CloudControlsPartnerCoreClient(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.CloudControlsPartnerCoreRestInterceptor, "post_get_partner" + ) as post, mock.patch.object( + transports.CloudControlsPartnerCoreRestInterceptor, "pre_get_partner" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = partners.GetPartnerRequest.pb(partners.GetPartnerRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = partners.Partner.to_json(partners.Partner()) + + request = partners.GetPartnerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = partners.Partner() + + client.get_partner( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_partner_rest_bad_request( + transport: str = "rest", request_type=partners.GetPartnerRequest +): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/locations/sample2/partner"} + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_partner(request) + + +def test_get_partner_rest_flattened(): + client = CloudControlsPartnerCoreClient( + 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 = partners.Partner() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/locations/sample2/partner"} + + # 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 = partners.Partner.pb(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_partner(**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=organizations/*/locations/*/partner}" % client.transport._host, + args[1], + ) + + +def test_get_partner_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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_partner( + partners.GetPartnerRequest(), + name="name_value", + ) + + +def test_get_partner_rest_error(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CloudControlsPartnerCoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CloudControlsPartnerCoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudControlsPartnerCoreClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CloudControlsPartnerCoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CloudControlsPartnerCoreClient( + 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 = CloudControlsPartnerCoreClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CloudControlsPartnerCoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudControlsPartnerCoreClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudControlsPartnerCoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CloudControlsPartnerCoreClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudControlsPartnerCoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CloudControlsPartnerCoreGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerCoreGrpcTransport, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + transports.CloudControlsPartnerCoreRestTransport, + ], +) +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() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = CloudControlsPartnerCoreClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CloudControlsPartnerCoreGrpcTransport, + ) + + +def test_cloud_controls_partner_core_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CloudControlsPartnerCoreTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_cloud_controls_partner_core_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_core.transports.CloudControlsPartnerCoreTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.CloudControlsPartnerCoreTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_workload", + "list_workloads", + "get_customer", + "list_customers", + "get_ekm_connections", + "get_partner_permissions", + "list_access_approval_requests", + "get_partner", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_cloud_controls_partner_core_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_core.transports.CloudControlsPartnerCoreTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudControlsPartnerCoreTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_cloud_controls_partner_core_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_core.transports.CloudControlsPartnerCoreTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudControlsPartnerCoreTransport() + adc.assert_called_once() + + +def test_cloud_controls_partner_core_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CloudControlsPartnerCoreClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerCoreGrpcTransport, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + ], +) +def test_cloud_controls_partner_core_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerCoreGrpcTransport, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + transports.CloudControlsPartnerCoreRestTransport, + ], +) +def test_cloud_controls_partner_core_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudControlsPartnerCoreGrpcTransport, grpc_helpers), + (transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_cloud_controls_partner_core_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudcontrolspartner.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="cloudcontrolspartner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerCoreGrpcTransport, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + ], +) +def test_cloud_controls_partner_core_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_cloud_controls_partner_core_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.CloudControlsPartnerCoreRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_cloud_controls_partner_core_host_no_port(transport_name): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudcontrolspartner.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudcontrolspartner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudcontrolspartner.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_cloud_controls_partner_core_host_with_port(transport_name): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudcontrolspartner.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudcontrolspartner.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudcontrolspartner.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_cloud_controls_partner_core_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CloudControlsPartnerCoreClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CloudControlsPartnerCoreClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_workload._session + session2 = client2.transport.get_workload._session + assert session1 != session2 + session1 = client1.transport.list_workloads._session + session2 = client2.transport.list_workloads._session + assert session1 != session2 + session1 = client1.transport.get_customer._session + session2 = client2.transport.get_customer._session + assert session1 != session2 + session1 = client1.transport.list_customers._session + session2 = client2.transport.list_customers._session + assert session1 != session2 + session1 = client1.transport.get_ekm_connections._session + session2 = client2.transport.get_ekm_connections._session + assert session1 != session2 + session1 = client1.transport.get_partner_permissions._session + session2 = client2.transport.get_partner_permissions._session + assert session1 != session2 + session1 = client1.transport.list_access_approval_requests._session + session2 = client2.transport.list_access_approval_requests._session + assert session1 != session2 + session1 = client1.transport.get_partner._session + session2 = client2.transport.get_partner._session + assert session1 != session2 + + +def test_cloud_controls_partner_core_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudControlsPartnerCoreGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_cloud_controls_partner_core_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudControlsPartnerCoreGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerCoreGrpcTransport, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + ], +) +def test_cloud_controls_partner_core_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerCoreGrpcTransport, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + ], +) +def test_cloud_controls_partner_core_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_access_approval_request_path(): + organization = "squid" + location = "clam" + customer = "whelk" + workload = "octopus" + access_approval_request = "oyster" + expected = "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/accessApprovalRequests/{access_approval_request}".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + access_approval_request=access_approval_request, + ) + actual = CloudControlsPartnerCoreClient.access_approval_request_path( + organization, location, customer, workload, access_approval_request + ) + assert expected == actual + + +def test_parse_access_approval_request_path(): + expected = { + "organization": "nudibranch", + "location": "cuttlefish", + "customer": "mussel", + "workload": "winkle", + "access_approval_request": "nautilus", + } + path = CloudControlsPartnerCoreClient.access_approval_request_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_access_approval_request_path(path) + assert expected == actual + + +def test_customer_path(): + organization = "scallop" + location = "abalone" + customer = "squid" + expected = ( + "organizations/{organization}/locations/{location}/customers/{customer}".format( + organization=organization, + location=location, + customer=customer, + ) + ) + actual = CloudControlsPartnerCoreClient.customer_path( + organization, location, customer + ) + assert expected == actual + + +def test_parse_customer_path(): + expected = { + "organization": "clam", + "location": "whelk", + "customer": "octopus", + } + path = CloudControlsPartnerCoreClient.customer_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_customer_path(path) + assert expected == actual + + +def test_ekm_connections_path(): + organization = "oyster" + location = "nudibranch" + customer = "cuttlefish" + workload = "mussel" + expected = "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/ekmConnections".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + ) + actual = CloudControlsPartnerCoreClient.ekm_connections_path( + organization, location, customer, workload + ) + assert expected == actual + + +def test_parse_ekm_connections_path(): + expected = { + "organization": "winkle", + "location": "nautilus", + "customer": "scallop", + "workload": "abalone", + } + path = CloudControlsPartnerCoreClient.ekm_connections_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_ekm_connections_path(path) + assert expected == actual + + +def test_partner_path(): + organization = "squid" + location = "clam" + expected = "organizations/{organization}/locations/{location}/partner".format( + organization=organization, + location=location, + ) + actual = CloudControlsPartnerCoreClient.partner_path(organization, location) + assert expected == actual + + +def test_parse_partner_path(): + expected = { + "organization": "whelk", + "location": "octopus", + } + path = CloudControlsPartnerCoreClient.partner_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_partner_path(path) + assert expected == actual + + +def test_partner_permissions_path(): + organization = "oyster" + location = "nudibranch" + customer = "cuttlefish" + workload = "mussel" + expected = "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/partnerPermissions".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + ) + actual = CloudControlsPartnerCoreClient.partner_permissions_path( + organization, location, customer, workload + ) + assert expected == actual + + +def test_parse_partner_permissions_path(): + expected = { + "organization": "winkle", + "location": "nautilus", + "customer": "scallop", + "workload": "abalone", + } + path = CloudControlsPartnerCoreClient.partner_permissions_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_partner_permissions_path(path) + assert expected == actual + + +def test_workload_path(): + organization = "squid" + location = "clam" + customer = "whelk" + workload = "octopus" + expected = "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + ) + actual = CloudControlsPartnerCoreClient.workload_path( + organization, location, customer, workload + ) + assert expected == actual + + +def test_parse_workload_path(): + expected = { + "organization": "oyster", + "location": "nudibranch", + "customer": "cuttlefish", + "workload": "mussel", + } + path = CloudControlsPartnerCoreClient.workload_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_workload_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = CloudControlsPartnerCoreClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = CloudControlsPartnerCoreClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = CloudControlsPartnerCoreClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = CloudControlsPartnerCoreClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = CloudControlsPartnerCoreClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = CloudControlsPartnerCoreClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format( + project=project, + ) + actual = CloudControlsPartnerCoreClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = CloudControlsPartnerCoreClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = CloudControlsPartnerCoreClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = CloudControlsPartnerCoreClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.CloudControlsPartnerCoreTransport, "_prep_wrapped_messages" + ) as prep: + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.CloudControlsPartnerCoreTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = CloudControlsPartnerCoreClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreGrpcTransport, + ), + ( + CloudControlsPartnerCoreAsyncClient, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-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 new file mode 100644 index 000000000000..f21e466a3d36 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1/test_cloud_controls_partner_monitoring.py @@ -0,0 +1,3327 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import Iterable +import json +import math + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import json_format +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import interval_pb2 # type: ignore +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +from google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_monitoring import ( + CloudControlsPartnerMonitoringAsyncClient, + CloudControlsPartnerMonitoringClient, + pagers, + transports, +) +from google.cloud.cloudcontrolspartner_v1.types import violations + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CloudControlsPartnerMonitoringClient._get_default_mtls_endpoint(None) is None + assert ( + CloudControlsPartnerMonitoringClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + CloudControlsPartnerMonitoringClient._get_default_mtls_endpoint( + api_mtls_endpoint + ) + == api_mtls_endpoint + ) + assert ( + CloudControlsPartnerMonitoringClient._get_default_mtls_endpoint( + sandbox_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + CloudControlsPartnerMonitoringClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + CloudControlsPartnerMonitoringClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert CloudControlsPartnerMonitoringClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert CloudControlsPartnerMonitoringClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert CloudControlsPartnerMonitoringClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + CloudControlsPartnerMonitoringClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert CloudControlsPartnerMonitoringClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert CloudControlsPartnerMonitoringClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert CloudControlsPartnerMonitoringClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + CloudControlsPartnerMonitoringClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert CloudControlsPartnerMonitoringClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert ( + CloudControlsPartnerMonitoringClient._get_client_cert_source(None, False) + is None + ) + assert ( + CloudControlsPartnerMonitoringClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + CloudControlsPartnerMonitoringClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + CloudControlsPartnerMonitoringClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + CloudControlsPartnerMonitoringClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + CloudControlsPartnerMonitoringClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerMonitoringClient), +) +@mock.patch.object( + CloudControlsPartnerMonitoringAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerMonitoringAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = CloudControlsPartnerMonitoringClient._DEFAULT_UNIVERSE + default_endpoint = ( + CloudControlsPartnerMonitoringClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = ( + CloudControlsPartnerMonitoringClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + ) + + assert ( + CloudControlsPartnerMonitoringClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + CloudControlsPartnerMonitoringClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == CloudControlsPartnerMonitoringClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + CloudControlsPartnerMonitoringClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + CloudControlsPartnerMonitoringClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == CloudControlsPartnerMonitoringClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + CloudControlsPartnerMonitoringClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == CloudControlsPartnerMonitoringClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + CloudControlsPartnerMonitoringClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + CloudControlsPartnerMonitoringClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + CloudControlsPartnerMonitoringClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + CloudControlsPartnerMonitoringClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + CloudControlsPartnerMonitoringClient._get_universe_domain( + None, universe_domain_env + ) + == universe_domain_env + ) + assert ( + CloudControlsPartnerMonitoringClient._get_universe_domain(None, None) + == CloudControlsPartnerMonitoringClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + CloudControlsPartnerMonitoringClient._get_universe_domain("", None) + 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", + [ + (CloudControlsPartnerMonitoringClient, "grpc"), + (CloudControlsPartnerMonitoringAsyncClient, "grpc_asyncio"), + (CloudControlsPartnerMonitoringClient, "rest"), + ], +) +def test_cloud_controls_partner_monitoring_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "cloudcontrolspartner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudcontrolspartner.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.CloudControlsPartnerMonitoringGrpcTransport, "grpc"), + (transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.CloudControlsPartnerMonitoringRestTransport, "rest"), + ], +) +def test_cloud_controls_partner_monitoring_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (CloudControlsPartnerMonitoringClient, "grpc"), + (CloudControlsPartnerMonitoringAsyncClient, "grpc_asyncio"), + (CloudControlsPartnerMonitoringClient, "rest"), + ], +) +def test_cloud_controls_partner_monitoring_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "cloudcontrolspartner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudcontrolspartner.googleapis.com" + ) + + +def test_cloud_controls_partner_monitoring_client_get_transport_class(): + transport = CloudControlsPartnerMonitoringClient.get_transport_class() + available_transports = [ + transports.CloudControlsPartnerMonitoringGrpcTransport, + transports.CloudControlsPartnerMonitoringRestTransport, + ] + assert transport in available_transports + + transport = CloudControlsPartnerMonitoringClient.get_transport_class("grpc") + assert transport == transports.CloudControlsPartnerMonitoringGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringGrpcTransport, + "grpc", + ), + ( + CloudControlsPartnerMonitoringAsyncClient, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + CloudControlsPartnerMonitoringClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerMonitoringClient), +) +@mock.patch.object( + CloudControlsPartnerMonitoringAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerMonitoringAsyncClient), +) +def test_cloud_controls_partner_monitoring_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object( + CloudControlsPartnerMonitoringClient, "get_transport_class" + ) as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object( + CloudControlsPartnerMonitoringClient, "get_transport_class" + ) as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringGrpcTransport, + "grpc", + "true", + ), + ( + CloudControlsPartnerMonitoringAsyncClient, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringGrpcTransport, + "grpc", + "false", + ), + ( + CloudControlsPartnerMonitoringAsyncClient, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringRestTransport, + "rest", + "true", + ), + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + CloudControlsPartnerMonitoringClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerMonitoringClient), +) +@mock.patch.object( + CloudControlsPartnerMonitoringAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerMonitoringAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_cloud_controls_partner_monitoring_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", + [CloudControlsPartnerMonitoringClient, CloudControlsPartnerMonitoringAsyncClient], +) +@mock.patch.object( + CloudControlsPartnerMonitoringClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudControlsPartnerMonitoringClient), +) +@mock.patch.object( + CloudControlsPartnerMonitoringAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudControlsPartnerMonitoringAsyncClient), +) +def test_cloud_controls_partner_monitoring_client_get_mtls_endpoint_and_cert_source( + client_class, +): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize( + "client_class", + [CloudControlsPartnerMonitoringClient, CloudControlsPartnerMonitoringAsyncClient], +) +@mock.patch.object( + CloudControlsPartnerMonitoringClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerMonitoringClient), +) +@mock.patch.object( + CloudControlsPartnerMonitoringAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerMonitoringAsyncClient), +) +def test_cloud_controls_partner_monitoring_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = CloudControlsPartnerMonitoringClient._DEFAULT_UNIVERSE + default_endpoint = ( + CloudControlsPartnerMonitoringClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = ( + CloudControlsPartnerMonitoringClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringGrpcTransport, + "grpc", + ), + ( + CloudControlsPartnerMonitoringAsyncClient, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringRestTransport, + "rest", + ), + ], +) +def test_cloud_controls_partner_monitoring_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + CloudControlsPartnerMonitoringAsyncClient, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringRestTransport, + "rest", + None, + ), + ], +) +def test_cloud_controls_partner_monitoring_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_cloud_controls_partner_monitoring_client_client_options_from_dict(): + with mock.patch( + "google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_monitoring.transports.CloudControlsPartnerMonitoringGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = CloudControlsPartnerMonitoringClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + CloudControlsPartnerMonitoringAsyncClient, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_cloud_controls_partner_monitoring_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudcontrolspartner.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="cloudcontrolspartner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + violations.ListViolationsRequest, + dict, + ], +) +def test_list_violations(request_type, transport: str = "grpc"): + client = CloudControlsPartnerMonitoringClient( + 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_violations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = violations.ListViolationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_violations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == violations.ListViolationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListViolationsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_violations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_violations), "__call__") as call: + client.list_violations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == violations.ListViolationsRequest() + + +@pytest.mark.asyncio +async def test_list_violations_async( + transport: str = "grpc_asyncio", request_type=violations.ListViolationsRequest +): + client = CloudControlsPartnerMonitoringAsyncClient( + 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_violations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + violations.ListViolationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_violations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == violations.ListViolationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListViolationsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_violations_async_from_dict(): + await test_list_violations_async(request_type=dict) + + +def test_list_violations_field_headers(): + client = CloudControlsPartnerMonitoringClient( + 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 = violations.ListViolationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_violations), "__call__") as call: + call.return_value = violations.ListViolationsResponse() + client.list_violations(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_violations_field_headers_async(): + client = CloudControlsPartnerMonitoringAsyncClient( + 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 = violations.ListViolationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_violations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + violations.ListViolationsResponse() + ) + await client.list_violations(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_violations_flattened(): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_violations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = violations.ListViolationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_violations( + 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_violations_flattened_error(): + client = CloudControlsPartnerMonitoringClient( + 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_violations( + violations.ListViolationsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_violations_flattened_async(): + client = CloudControlsPartnerMonitoringAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_violations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = violations.ListViolationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + violations.ListViolationsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_violations( + 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_violations_flattened_error_async(): + client = CloudControlsPartnerMonitoringAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_violations( + violations.ListViolationsRequest(), + parent="parent_value", + ) + + +def test_list_violations_pager(transport_name: str = "grpc"): + client = CloudControlsPartnerMonitoringClient( + 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_violations), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + violations.Violation(), + ], + next_page_token="abc", + ), + violations.ListViolationsResponse( + violations=[], + next_page_token="def", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + ], + next_page_token="ghi", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_violations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, violations.Violation) for i in results) + + +def test_list_violations_pages(transport_name: str = "grpc"): + client = CloudControlsPartnerMonitoringClient( + 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_violations), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + violations.Violation(), + ], + next_page_token="abc", + ), + violations.ListViolationsResponse( + violations=[], + next_page_token="def", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + ], + next_page_token="ghi", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_violations(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_violations_async_pager(): + client = CloudControlsPartnerMonitoringAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_violations), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + violations.Violation(), + ], + next_page_token="abc", + ), + violations.ListViolationsResponse( + violations=[], + next_page_token="def", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + ], + next_page_token="ghi", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_violations( + 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, violations.Violation) for i in responses) + + +@pytest.mark.asyncio +async def test_list_violations_async_pages(): + client = CloudControlsPartnerMonitoringAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_violations), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + violations.Violation(), + ], + next_page_token="abc", + ), + violations.ListViolationsResponse( + violations=[], + next_page_token="def", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + ], + next_page_token="ghi", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + ], + ), + 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_violations(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", + [ + violations.GetViolationRequest, + dict, + ], +) +def test_get_violation(request_type, transport: str = "grpc"): + client = CloudControlsPartnerMonitoringClient( + 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_violation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = violations.Violation( + name="name_value", + description="description_value", + category="category_value", + state=violations.Violation.State.RESOLVED, + non_compliant_org_policy="non_compliant_org_policy_value", + folder_id=936, + ) + response = client.get_violation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == violations.GetViolationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, violations.Violation) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.category == "category_value" + assert response.state == violations.Violation.State.RESOLVED + assert response.non_compliant_org_policy == "non_compliant_org_policy_value" + assert response.folder_id == 936 + + +def test_get_violation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_violation), "__call__") as call: + client.get_violation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == violations.GetViolationRequest() + + +@pytest.mark.asyncio +async def test_get_violation_async( + transport: str = "grpc_asyncio", request_type=violations.GetViolationRequest +): + client = CloudControlsPartnerMonitoringAsyncClient( + 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_violation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + violations.Violation( + name="name_value", + description="description_value", + category="category_value", + state=violations.Violation.State.RESOLVED, + non_compliant_org_policy="non_compliant_org_policy_value", + folder_id=936, + ) + ) + response = await client.get_violation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == violations.GetViolationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, violations.Violation) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.category == "category_value" + assert response.state == violations.Violation.State.RESOLVED + assert response.non_compliant_org_policy == "non_compliant_org_policy_value" + assert response.folder_id == 936 + + +@pytest.mark.asyncio +async def test_get_violation_async_from_dict(): + await test_get_violation_async(request_type=dict) + + +def test_get_violation_field_headers(): + client = CloudControlsPartnerMonitoringClient( + 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 = violations.GetViolationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_violation), "__call__") as call: + call.return_value = violations.Violation() + client.get_violation(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_violation_field_headers_async(): + client = CloudControlsPartnerMonitoringAsyncClient( + 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 = violations.GetViolationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_violation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + violations.Violation() + ) + await client.get_violation(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_violation_flattened(): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_violation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = violations.Violation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_violation( + 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_violation_flattened_error(): + client = CloudControlsPartnerMonitoringClient( + 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_violation( + violations.GetViolationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_violation_flattened_async(): + client = CloudControlsPartnerMonitoringAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_violation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = violations.Violation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + violations.Violation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_violation( + 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_violation_flattened_error_async(): + client = CloudControlsPartnerMonitoringAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_violation( + violations.GetViolationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + violations.ListViolationsRequest, + dict, + ], +) +def test_list_violations_rest(request_type): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "organizations/sample1/locations/sample2/customers/sample3/workloads/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 = violations.ListViolationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = violations.ListViolationsResponse.pb(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_violations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListViolationsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_violations_rest_required_fields( + request_type=violations.ListViolationsRequest, +): + transport_class = transports.CloudControlsPartnerMonitoringRestTransport + + 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_violations._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_violations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "interval", + "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 = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = violations.ListViolationsResponse() + # 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 = violations.ListViolationsResponse.pb(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_violations(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_violations_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerMonitoringRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_violations._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "interval", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_violations_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerMonitoringRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerMonitoringRestInterceptor(), + ) + client = CloudControlsPartnerMonitoringClient(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.CloudControlsPartnerMonitoringRestInterceptor, "post_list_violations" + ) as post, mock.patch.object( + transports.CloudControlsPartnerMonitoringRestInterceptor, "pre_list_violations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = violations.ListViolationsRequest.pb( + violations.ListViolationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = violations.ListViolationsResponse.to_json( + violations.ListViolationsResponse() + ) + + request = violations.ListViolationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = violations.ListViolationsResponse() + + client.list_violations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_violations_rest_bad_request( + transport: str = "rest", request_type=violations.ListViolationsRequest +): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "organizations/sample1/locations/sample2/customers/sample3/workloads/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_violations(request) + + +def test_list_violations_rest_flattened(): + client = CloudControlsPartnerMonitoringClient( + 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 = violations.ListViolationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4" + } + + # 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 = violations.ListViolationsResponse.pb(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_violations(**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=organizations/*/locations/*/customers/*/workloads/*}/violations" + % client.transport._host, + args[1], + ) + + +def test_list_violations_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerMonitoringClient( + 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_violations( + violations.ListViolationsRequest(), + parent="parent_value", + ) + + +def test_list_violations_rest_pager(transport: str = "rest"): + client = CloudControlsPartnerMonitoringClient( + 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 = ( + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + violations.Violation(), + ], + next_page_token="abc", + ), + violations.ListViolationsResponse( + violations=[], + next_page_token="def", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + ], + next_page_token="ghi", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(violations.ListViolationsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4" + } + + pager = client.list_violations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, violations.Violation) for i in results) + + pages = list(client.list_violations(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + violations.GetViolationRequest, + dict, + ], +) +def test_get_violation_rest(request_type): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/violations/sample5" + } + 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 = violations.Violation( + name="name_value", + description="description_value", + category="category_value", + state=violations.Violation.State.RESOLVED, + non_compliant_org_policy="non_compliant_org_policy_value", + folder_id=936, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = violations.Violation.pb(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_violation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, violations.Violation) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.category == "category_value" + assert response.state == violations.Violation.State.RESOLVED + assert response.non_compliant_org_policy == "non_compliant_org_policy_value" + assert response.folder_id == 936 + + +def test_get_violation_rest_required_fields( + request_type=violations.GetViolationRequest, +): + transport_class = transports.CloudControlsPartnerMonitoringRestTransport + + 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_violation._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_violation._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 = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = violations.Violation() + # 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 = violations.Violation.pb(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_violation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_violation_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerMonitoringRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_violation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_violation_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerMonitoringRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerMonitoringRestInterceptor(), + ) + client = CloudControlsPartnerMonitoringClient(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.CloudControlsPartnerMonitoringRestInterceptor, "post_get_violation" + ) as post, mock.patch.object( + transports.CloudControlsPartnerMonitoringRestInterceptor, "pre_get_violation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = violations.GetViolationRequest.pb(violations.GetViolationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = violations.Violation.to_json(violations.Violation()) + + request = violations.GetViolationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = violations.Violation() + + client.get_violation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_violation_rest_bad_request( + transport: str = "rest", request_type=violations.GetViolationRequest +): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/violations/sample5" + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_violation(request) + + +def test_get_violation_rest_flattened(): + client = CloudControlsPartnerMonitoringClient( + 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 = violations.Violation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/violations/sample5" + } + + # 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 = violations.Violation.pb(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_violation(**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=organizations/*/locations/*/customers/*/workloads/*/violations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_violation_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerMonitoringClient( + 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_violation( + violations.GetViolationRequest(), + name="name_value", + ) + + +def test_get_violation_rest_error(): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CloudControlsPartnerMonitoringGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CloudControlsPartnerMonitoringGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudControlsPartnerMonitoringClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CloudControlsPartnerMonitoringGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CloudControlsPartnerMonitoringClient( + 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 = CloudControlsPartnerMonitoringClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CloudControlsPartnerMonitoringGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudControlsPartnerMonitoringClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudControlsPartnerMonitoringGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CloudControlsPartnerMonitoringClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudControlsPartnerMonitoringGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerMonitoringGrpcTransport, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + transports.CloudControlsPartnerMonitoringRestTransport, + ], +) +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() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = CloudControlsPartnerMonitoringClient.get_transport_class( + transport_name + )( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CloudControlsPartnerMonitoringGrpcTransport, + ) + + +def test_cloud_controls_partner_monitoring_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CloudControlsPartnerMonitoringTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_cloud_controls_partner_monitoring_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_monitoring.transports.CloudControlsPartnerMonitoringTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.CloudControlsPartnerMonitoringTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_violations", + "get_violation", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_cloud_controls_partner_monitoring_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_monitoring.transports.CloudControlsPartnerMonitoringTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudControlsPartnerMonitoringTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_cloud_controls_partner_monitoring_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.cloudcontrolspartner_v1.services.cloud_controls_partner_monitoring.transports.CloudControlsPartnerMonitoringTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudControlsPartnerMonitoringTransport() + adc.assert_called_once() + + +def test_cloud_controls_partner_monitoring_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CloudControlsPartnerMonitoringClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerMonitoringGrpcTransport, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + ], +) +def test_cloud_controls_partner_monitoring_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerMonitoringGrpcTransport, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + transports.CloudControlsPartnerMonitoringRestTransport, + ], +) +def test_cloud_controls_partner_monitoring_transport_auth_gdch_credentials( + transport_class, +): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudControlsPartnerMonitoringGrpcTransport, grpc_helpers), + ( + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + grpc_helpers_async, + ), + ], +) +def test_cloud_controls_partner_monitoring_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudcontrolspartner.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="cloudcontrolspartner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerMonitoringGrpcTransport, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + ], +) +def test_cloud_controls_partner_monitoring_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_cloud_controls_partner_monitoring_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.CloudControlsPartnerMonitoringRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_cloud_controls_partner_monitoring_host_no_port(transport_name): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudcontrolspartner.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudcontrolspartner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudcontrolspartner.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_cloud_controls_partner_monitoring_host_with_port(transport_name): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudcontrolspartner.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudcontrolspartner.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudcontrolspartner.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_cloud_controls_partner_monitoring_client_transport_session_collision( + transport_name, +): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CloudControlsPartnerMonitoringClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CloudControlsPartnerMonitoringClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_violations._session + session2 = client2.transport.list_violations._session + assert session1 != session2 + session1 = client1.transport.get_violation._session + session2 = client2.transport.get_violation._session + assert session1 != session2 + + +def test_cloud_controls_partner_monitoring_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudControlsPartnerMonitoringGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_cloud_controls_partner_monitoring_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerMonitoringGrpcTransport, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + ], +) +def test_cloud_controls_partner_monitoring_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerMonitoringGrpcTransport, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + ], +) +def test_cloud_controls_partner_monitoring_transport_channel_mtls_with_adc( + transport_class, +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_violation_path(): + organization = "squid" + location = "clam" + customer = "whelk" + workload = "octopus" + violation = "oyster" + expected = "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/violations/{violation}".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + violation=violation, + ) + actual = CloudControlsPartnerMonitoringClient.violation_path( + organization, location, customer, workload, violation + ) + assert expected == actual + + +def test_parse_violation_path(): + expected = { + "organization": "nudibranch", + "location": "cuttlefish", + "customer": "mussel", + "workload": "winkle", + "violation": "nautilus", + } + path = CloudControlsPartnerMonitoringClient.violation_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerMonitoringClient.parse_violation_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = CloudControlsPartnerMonitoringClient.common_billing_account_path( + billing_account + ) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = CloudControlsPartnerMonitoringClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerMonitoringClient.parse_common_billing_account_path( + path + ) + assert expected == actual + + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = CloudControlsPartnerMonitoringClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = CloudControlsPartnerMonitoringClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerMonitoringClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = CloudControlsPartnerMonitoringClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = CloudControlsPartnerMonitoringClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerMonitoringClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format( + project=project, + ) + actual = CloudControlsPartnerMonitoringClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = CloudControlsPartnerMonitoringClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerMonitoringClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = CloudControlsPartnerMonitoringClient.common_location_path( + project, location + ) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = CloudControlsPartnerMonitoringClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerMonitoringClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.CloudControlsPartnerMonitoringTransport, "_prep_wrapped_messages" + ) as prep: + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.CloudControlsPartnerMonitoringTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = CloudControlsPartnerMonitoringClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CloudControlsPartnerMonitoringAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringGrpcTransport, + ), + ( + CloudControlsPartnerMonitoringAsyncClient, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1beta/__init__.py b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1beta/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1beta/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# 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 new file mode 100644 index 000000000000..6e1fc0c93a97 --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1beta/test_cloud_controls_partner_core.py @@ -0,0 +1,7154 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import Iterable +import json +import math + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import json_format +from google.protobuf import timestamp_pb2 # type: ignore +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +from google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core import ( + CloudControlsPartnerCoreAsyncClient, + CloudControlsPartnerCoreClient, + pagers, + transports, +) +from google.cloud.cloudcontrolspartner_v1beta.types import ( + access_approval_requests, + customer_workloads, + customers, + ekm_connections, + partner_permissions, + partners, +) + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CloudControlsPartnerCoreClient._get_default_mtls_endpoint(None) is None + assert ( + CloudControlsPartnerCoreClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + CloudControlsPartnerCoreClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + CloudControlsPartnerCoreClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + CloudControlsPartnerCoreClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + CloudControlsPartnerCoreClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert CloudControlsPartnerCoreClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert CloudControlsPartnerCoreClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert CloudControlsPartnerCoreClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + CloudControlsPartnerCoreClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert CloudControlsPartnerCoreClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert CloudControlsPartnerCoreClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert CloudControlsPartnerCoreClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + CloudControlsPartnerCoreClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert CloudControlsPartnerCoreClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert CloudControlsPartnerCoreClient._get_client_cert_source(None, False) is None + assert ( + CloudControlsPartnerCoreClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + CloudControlsPartnerCoreClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + CloudControlsPartnerCoreClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + CloudControlsPartnerCoreClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + CloudControlsPartnerCoreClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerCoreClient), +) +@mock.patch.object( + CloudControlsPartnerCoreAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerCoreAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = CloudControlsPartnerCoreClient._DEFAULT_UNIVERSE + default_endpoint = CloudControlsPartnerCoreClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = CloudControlsPartnerCoreClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + CloudControlsPartnerCoreClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + CloudControlsPartnerCoreClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == CloudControlsPartnerCoreClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + CloudControlsPartnerCoreClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + CloudControlsPartnerCoreClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == CloudControlsPartnerCoreClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + CloudControlsPartnerCoreClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == CloudControlsPartnerCoreClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + CloudControlsPartnerCoreClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + CloudControlsPartnerCoreClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + CloudControlsPartnerCoreClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + CloudControlsPartnerCoreClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + CloudControlsPartnerCoreClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + CloudControlsPartnerCoreClient._get_universe_domain(None, None) + == CloudControlsPartnerCoreClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + CloudControlsPartnerCoreClient._get_universe_domain("", None) + 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", + [ + (CloudControlsPartnerCoreClient, "grpc"), + (CloudControlsPartnerCoreAsyncClient, "grpc_asyncio"), + (CloudControlsPartnerCoreClient, "rest"), + ], +) +def test_cloud_controls_partner_core_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "cloudcontrolspartner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudcontrolspartner.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.CloudControlsPartnerCoreGrpcTransport, "grpc"), + (transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.CloudControlsPartnerCoreRestTransport, "rest"), + ], +) +def test_cloud_controls_partner_core_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (CloudControlsPartnerCoreClient, "grpc"), + (CloudControlsPartnerCoreAsyncClient, "grpc_asyncio"), + (CloudControlsPartnerCoreClient, "rest"), + ], +) +def test_cloud_controls_partner_core_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "cloudcontrolspartner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudcontrolspartner.googleapis.com" + ) + + +def test_cloud_controls_partner_core_client_get_transport_class(): + transport = CloudControlsPartnerCoreClient.get_transport_class() + available_transports = [ + transports.CloudControlsPartnerCoreGrpcTransport, + transports.CloudControlsPartnerCoreRestTransport, + ] + assert transport in available_transports + + transport = CloudControlsPartnerCoreClient.get_transport_class("grpc") + assert transport == transports.CloudControlsPartnerCoreGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreGrpcTransport, + "grpc", + ), + ( + CloudControlsPartnerCoreAsyncClient, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + CloudControlsPartnerCoreClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerCoreClient), +) +@mock.patch.object( + CloudControlsPartnerCoreAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerCoreAsyncClient), +) +def test_cloud_controls_partner_core_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object( + CloudControlsPartnerCoreClient, "get_transport_class" + ) as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object( + CloudControlsPartnerCoreClient, "get_transport_class" + ) as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreGrpcTransport, + "grpc", + "true", + ), + ( + CloudControlsPartnerCoreAsyncClient, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreGrpcTransport, + "grpc", + "false", + ), + ( + CloudControlsPartnerCoreAsyncClient, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreRestTransport, + "rest", + "true", + ), + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + CloudControlsPartnerCoreClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerCoreClient), +) +@mock.patch.object( + CloudControlsPartnerCoreAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerCoreAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_cloud_controls_partner_core_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", + [CloudControlsPartnerCoreClient, CloudControlsPartnerCoreAsyncClient], +) +@mock.patch.object( + CloudControlsPartnerCoreClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudControlsPartnerCoreClient), +) +@mock.patch.object( + CloudControlsPartnerCoreAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudControlsPartnerCoreAsyncClient), +) +def test_cloud_controls_partner_core_client_get_mtls_endpoint_and_cert_source( + client_class, +): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize( + "client_class", + [CloudControlsPartnerCoreClient, CloudControlsPartnerCoreAsyncClient], +) +@mock.patch.object( + CloudControlsPartnerCoreClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerCoreClient), +) +@mock.patch.object( + CloudControlsPartnerCoreAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerCoreAsyncClient), +) +def test_cloud_controls_partner_core_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = CloudControlsPartnerCoreClient._DEFAULT_UNIVERSE + default_endpoint = CloudControlsPartnerCoreClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = CloudControlsPartnerCoreClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreGrpcTransport, + "grpc", + ), + ( + CloudControlsPartnerCoreAsyncClient, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreRestTransport, + "rest", + ), + ], +) +def test_cloud_controls_partner_core_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + CloudControlsPartnerCoreAsyncClient, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreRestTransport, + "rest", + None, + ), + ], +) +def test_cloud_controls_partner_core_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_cloud_controls_partner_core_client_client_options_from_dict(): + with mock.patch( + "google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.transports.CloudControlsPartnerCoreGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = CloudControlsPartnerCoreClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + CloudControlsPartnerCoreAsyncClient, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_cloud_controls_partner_core_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudcontrolspartner.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="cloudcontrolspartner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + customer_workloads.GetWorkloadRequest, + dict, + ], +) +def test_get_workload(request_type, transport: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_workload), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customer_workloads.Workload( + name="name_value", + folder_id=936, + folder="folder_value", + is_onboarded=True, + key_management_project_id="key_management_project_id_value", + location="location_value", + partner=customer_workloads.Workload.Partner.PARTNER_LOCAL_CONTROLS_BY_S3NS, + ) + response = client.get_workload(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == customer_workloads.GetWorkloadRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, customer_workloads.Workload) + assert response.name == "name_value" + assert response.folder_id == 936 + assert response.folder == "folder_value" + assert response.is_onboarded is True + assert response.key_management_project_id == "key_management_project_id_value" + assert response.location == "location_value" + assert ( + response.partner + == customer_workloads.Workload.Partner.PARTNER_LOCAL_CONTROLS_BY_S3NS + ) + + +def test_get_workload_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_workload), "__call__") as call: + client.get_workload() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == customer_workloads.GetWorkloadRequest() + + +@pytest.mark.asyncio +async def test_get_workload_async( + transport: str = "grpc_asyncio", request_type=customer_workloads.GetWorkloadRequest +): + client = CloudControlsPartnerCoreAsyncClient( + 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_workload), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customer_workloads.Workload( + name="name_value", + folder_id=936, + folder="folder_value", + is_onboarded=True, + key_management_project_id="key_management_project_id_value", + location="location_value", + partner=customer_workloads.Workload.Partner.PARTNER_LOCAL_CONTROLS_BY_S3NS, + ) + ) + response = await client.get_workload(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == customer_workloads.GetWorkloadRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, customer_workloads.Workload) + assert response.name == "name_value" + assert response.folder_id == 936 + assert response.folder == "folder_value" + assert response.is_onboarded is True + assert response.key_management_project_id == "key_management_project_id_value" + assert response.location == "location_value" + assert ( + response.partner + == customer_workloads.Workload.Partner.PARTNER_LOCAL_CONTROLS_BY_S3NS + ) + + +@pytest.mark.asyncio +async def test_get_workload_async_from_dict(): + await test_get_workload_async(request_type=dict) + + +def test_get_workload_field_headers(): + client = CloudControlsPartnerCoreClient( + 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 = customer_workloads.GetWorkloadRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_workload), "__call__") as call: + call.return_value = customer_workloads.Workload() + client.get_workload(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_workload_field_headers_async(): + client = CloudControlsPartnerCoreAsyncClient( + 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 = customer_workloads.GetWorkloadRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_workload), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customer_workloads.Workload() + ) + await client.get_workload(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_workload_flattened(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_workload), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customer_workloads.Workload() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_workload( + 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_workload_flattened_error(): + client = CloudControlsPartnerCoreClient( + 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_workload( + customer_workloads.GetWorkloadRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_workload_flattened_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_workload), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customer_workloads.Workload() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customer_workloads.Workload() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_workload( + 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_workload_flattened_error_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_workload( + customer_workloads.GetWorkloadRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + customer_workloads.ListWorkloadsRequest, + dict, + ], +) +def test_list_workloads(request_type, transport: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_workloads), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customer_workloads.ListWorkloadsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_workloads(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == customer_workloads.ListWorkloadsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkloadsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_workloads_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_workloads), "__call__") as call: + client.list_workloads() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == customer_workloads.ListWorkloadsRequest() + + +@pytest.mark.asyncio +async def test_list_workloads_async( + transport: str = "grpc_asyncio", + request_type=customer_workloads.ListWorkloadsRequest, +): + client = CloudControlsPartnerCoreAsyncClient( + 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_workloads), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customer_workloads.ListWorkloadsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_workloads(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == customer_workloads.ListWorkloadsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkloadsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_workloads_async_from_dict(): + await test_list_workloads_async(request_type=dict) + + +def test_list_workloads_field_headers(): + client = CloudControlsPartnerCoreClient( + 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 = customer_workloads.ListWorkloadsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_workloads), "__call__") as call: + call.return_value = customer_workloads.ListWorkloadsResponse() + client.list_workloads(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_workloads_field_headers_async(): + client = CloudControlsPartnerCoreAsyncClient( + 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 = customer_workloads.ListWorkloadsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_workloads), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customer_workloads.ListWorkloadsResponse() + ) + await client.list_workloads(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_workloads_flattened(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_workloads), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customer_workloads.ListWorkloadsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_workloads( + 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_workloads_flattened_error(): + client = CloudControlsPartnerCoreClient( + 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_workloads( + customer_workloads.ListWorkloadsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_workloads_flattened_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_workloads), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customer_workloads.ListWorkloadsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customer_workloads.ListWorkloadsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_workloads( + 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_workloads_flattened_error_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_workloads( + customer_workloads.ListWorkloadsRequest(), + parent="parent_value", + ) + + +def test_list_workloads_pager(transport_name: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_workloads), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + next_page_token="abc", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[], + next_page_token="def", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + ], + next_page_token="ghi", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_workloads(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, customer_workloads.Workload) for i in results) + + +def test_list_workloads_pages(transport_name: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_workloads), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + next_page_token="abc", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[], + next_page_token="def", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + ], + next_page_token="ghi", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + ), + RuntimeError, + ) + pages = list(client.list_workloads(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_workloads_async_pager(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + next_page_token="abc", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[], + next_page_token="def", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + ], + next_page_token="ghi", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_workloads( + 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, customer_workloads.Workload) for i in responses) + + +@pytest.mark.asyncio +async def test_list_workloads_async_pages(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_workloads), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + next_page_token="abc", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[], + next_page_token="def", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + ], + next_page_token="ghi", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + ), + 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_workloads(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", + [ + customers.GetCustomerRequest, + dict, + ], +) +def test_get_customer(request_type, transport: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_customer), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customers.Customer( + name="name_value", + display_name="display_name_value", + is_onboarded=True, + ) + response = client.get_customer(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == customers.GetCustomerRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, customers.Customer) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.is_onboarded is True + + +def test_get_customer_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_customer), "__call__") as call: + client.get_customer() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == customers.GetCustomerRequest() + + +@pytest.mark.asyncio +async def test_get_customer_async( + transport: str = "grpc_asyncio", request_type=customers.GetCustomerRequest +): + client = CloudControlsPartnerCoreAsyncClient( + 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_customer), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customers.Customer( + name="name_value", + display_name="display_name_value", + is_onboarded=True, + ) + ) + response = await client.get_customer(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == customers.GetCustomerRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, customers.Customer) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.is_onboarded is True + + +@pytest.mark.asyncio +async def test_get_customer_async_from_dict(): + await test_get_customer_async(request_type=dict) + + +def test_get_customer_field_headers(): + client = CloudControlsPartnerCoreClient( + 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 = customers.GetCustomerRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_customer), "__call__") as call: + call.return_value = customers.Customer() + client.get_customer(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_customer_field_headers_async(): + client = CloudControlsPartnerCoreAsyncClient( + 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 = customers.GetCustomerRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_customer), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(customers.Customer()) + await client.get_customer(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_customer_flattened(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_customer), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customers.Customer() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_customer( + 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_customer_flattened_error(): + client = CloudControlsPartnerCoreClient( + 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_customer( + customers.GetCustomerRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_customer_flattened_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_customer), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customers.Customer() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(customers.Customer()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_customer( + 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_customer_flattened_error_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_customer( + customers.GetCustomerRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + customers.ListCustomersRequest, + dict, + ], +) +def test_list_customers(request_type, transport: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_customers), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customers.ListCustomersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_customers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == customers.ListCustomersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_customers_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_customers), "__call__") as call: + client.list_customers() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == customers.ListCustomersRequest() + + +@pytest.mark.asyncio +async def test_list_customers_async( + transport: str = "grpc_asyncio", request_type=customers.ListCustomersRequest +): + client = CloudControlsPartnerCoreAsyncClient( + 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_customers), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customers.ListCustomersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_customers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == customers.ListCustomersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomersAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_customers_async_from_dict(): + await test_list_customers_async(request_type=dict) + + +def test_list_customers_field_headers(): + client = CloudControlsPartnerCoreClient( + 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 = customers.ListCustomersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_customers), "__call__") as call: + call.return_value = customers.ListCustomersResponse() + client.list_customers(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_customers_field_headers_async(): + client = CloudControlsPartnerCoreAsyncClient( + 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 = customers.ListCustomersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_customers), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customers.ListCustomersResponse() + ) + await client.list_customers(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_customers_flattened(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_customers), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customers.ListCustomersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_customers( + 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_customers_flattened_error(): + client = CloudControlsPartnerCoreClient( + 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_customers( + customers.ListCustomersRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_customers_flattened_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_customers), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = customers.ListCustomersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + customers.ListCustomersResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_customers( + 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_customers_flattened_error_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_customers( + customers.ListCustomersRequest(), + parent="parent_value", + ) + + +def test_list_customers_pager(transport_name: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_customers), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + customers.Customer(), + ], + next_page_token="abc", + ), + customers.ListCustomersResponse( + customers=[], + next_page_token="def", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + ], + next_page_token="ghi", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_customers(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, customers.Customer) for i in results) + + +def test_list_customers_pages(transport_name: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_customers), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + customers.Customer(), + ], + next_page_token="abc", + ), + customers.ListCustomersResponse( + customers=[], + next_page_token="def", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + ], + next_page_token="ghi", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + ], + ), + RuntimeError, + ) + pages = list(client.list_customers(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_customers_async_pager(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_customers), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + customers.Customer(), + ], + next_page_token="abc", + ), + customers.ListCustomersResponse( + customers=[], + next_page_token="def", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + ], + next_page_token="ghi", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_customers( + 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, customers.Customer) for i in responses) + + +@pytest.mark.asyncio +async def test_list_customers_async_pages(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_customers), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + customers.Customer(), + ], + next_page_token="abc", + ), + customers.ListCustomersResponse( + customers=[], + next_page_token="def", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + ], + next_page_token="ghi", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + ], + ), + 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_customers(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", + [ + ekm_connections.GetEkmConnectionsRequest, + dict, + ], +) +def test_get_ekm_connections(request_type, transport: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_ekm_connections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_connections.EkmConnections( + name="name_value", + ) + response = client.get_ekm_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] == ekm_connections.GetEkmConnectionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_connections.EkmConnections) + assert response.name == "name_value" + + +def test_get_ekm_connections_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connections), "__call__" + ) as call: + client.get_ekm_connections() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_connections.GetEkmConnectionsRequest() + + +@pytest.mark.asyncio +async def test_get_ekm_connections_async( + transport: str = "grpc_asyncio", + request_type=ekm_connections.GetEkmConnectionsRequest, +): + client = CloudControlsPartnerCoreAsyncClient( + 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_ekm_connections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_connections.EkmConnections( + name="name_value", + ) + ) + response = await client.get_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_connections.GetEkmConnectionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_connections.EkmConnections) + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_get_ekm_connections_async_from_dict(): + await test_get_ekm_connections_async(request_type=dict) + + +def test_get_ekm_connections_field_headers(): + client = CloudControlsPartnerCoreClient( + 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 = ekm_connections.GetEkmConnectionsRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connections), "__call__" + ) as call: + call.return_value = ekm_connections.EkmConnections() + client.get_ekm_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 + + # 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_ekm_connections_field_headers_async(): + client = CloudControlsPartnerCoreAsyncClient( + 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 = ekm_connections.GetEkmConnectionsRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connections), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_connections.EkmConnections() + ) + await client.get_ekm_connections(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_ekm_connections_flattened(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_connections.EkmConnections() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_ekm_connections( + 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_ekm_connections_flattened_error(): + client = CloudControlsPartnerCoreClient( + 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_ekm_connections( + ekm_connections.GetEkmConnectionsRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_ekm_connections_flattened_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_connections.EkmConnections() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_connections.EkmConnections() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_ekm_connections( + 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_ekm_connections_flattened_error_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_ekm_connections( + ekm_connections.GetEkmConnectionsRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + partner_permissions.GetPartnerPermissionsRequest, + dict, + ], +) +def test_get_partner_permissions(request_type, transport: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_partner_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = partner_permissions.PartnerPermissions( + name="name_value", + partner_permissions=[ + partner_permissions.PartnerPermissions.Permission.ACCESS_TRANSPARENCY_AND_EMERGENCY_ACCESS_LOGS + ], + ) + response = client.get_partner_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == partner_permissions.GetPartnerPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, partner_permissions.PartnerPermissions) + assert response.name == "name_value" + assert response.partner_permissions == [ + partner_permissions.PartnerPermissions.Permission.ACCESS_TRANSPARENCY_AND_EMERGENCY_ACCESS_LOGS + ] + + +def test_get_partner_permissions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_partner_permissions), "__call__" + ) as call: + client.get_partner_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == partner_permissions.GetPartnerPermissionsRequest() + + +@pytest.mark.asyncio +async def test_get_partner_permissions_async( + transport: str = "grpc_asyncio", + request_type=partner_permissions.GetPartnerPermissionsRequest, +): + client = CloudControlsPartnerCoreAsyncClient( + 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_partner_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + partner_permissions.PartnerPermissions( + name="name_value", + partner_permissions=[ + partner_permissions.PartnerPermissions.Permission.ACCESS_TRANSPARENCY_AND_EMERGENCY_ACCESS_LOGS + ], + ) + ) + response = await client.get_partner_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == partner_permissions.GetPartnerPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, partner_permissions.PartnerPermissions) + assert response.name == "name_value" + assert response.partner_permissions == [ + partner_permissions.PartnerPermissions.Permission.ACCESS_TRANSPARENCY_AND_EMERGENCY_ACCESS_LOGS + ] + + +@pytest.mark.asyncio +async def test_get_partner_permissions_async_from_dict(): + await test_get_partner_permissions_async(request_type=dict) + + +def test_get_partner_permissions_field_headers(): + client = CloudControlsPartnerCoreClient( + 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 = partner_permissions.GetPartnerPermissionsRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_partner_permissions), "__call__" + ) as call: + call.return_value = partner_permissions.PartnerPermissions() + client.get_partner_permissions(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_partner_permissions_field_headers_async(): + client = CloudControlsPartnerCoreAsyncClient( + 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 = partner_permissions.GetPartnerPermissionsRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_partner_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + partner_permissions.PartnerPermissions() + ) + await client.get_partner_permissions(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_partner_permissions_flattened(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_partner_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = partner_permissions.PartnerPermissions() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_partner_permissions( + 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_partner_permissions_flattened_error(): + client = CloudControlsPartnerCoreClient( + 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_partner_permissions( + partner_permissions.GetPartnerPermissionsRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_partner_permissions_flattened_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_partner_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = partner_permissions.PartnerPermissions() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + partner_permissions.PartnerPermissions() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_partner_permissions( + 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_partner_permissions_flattened_error_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_partner_permissions( + partner_permissions.GetPartnerPermissionsRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + access_approval_requests.ListAccessApprovalRequestsRequest, + dict, + ], +) +def test_list_access_approval_requests(request_type, transport: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_access_approval_requests), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = access_approval_requests.ListAccessApprovalRequestsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_access_approval_requests(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == access_approval_requests.ListAccessApprovalRequestsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccessApprovalRequestsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_access_approval_requests_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_approval_requests), "__call__" + ) as call: + client.list_access_approval_requests() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == access_approval_requests.ListAccessApprovalRequestsRequest() + + +@pytest.mark.asyncio +async def test_list_access_approval_requests_async( + transport: str = "grpc_asyncio", + request_type=access_approval_requests.ListAccessApprovalRequestsRequest, +): + client = CloudControlsPartnerCoreAsyncClient( + 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_access_approval_requests), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + access_approval_requests.ListAccessApprovalRequestsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_access_approval_requests(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == access_approval_requests.ListAccessApprovalRequestsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccessApprovalRequestsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_access_approval_requests_async_from_dict(): + await test_list_access_approval_requests_async(request_type=dict) + + +def test_list_access_approval_requests_field_headers(): + client = CloudControlsPartnerCoreClient( + 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 = access_approval_requests.ListAccessApprovalRequestsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_approval_requests), "__call__" + ) as call: + call.return_value = ( + access_approval_requests.ListAccessApprovalRequestsResponse() + ) + client.list_access_approval_requests(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_access_approval_requests_field_headers_async(): + client = CloudControlsPartnerCoreAsyncClient( + 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 = access_approval_requests.ListAccessApprovalRequestsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_approval_requests), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + access_approval_requests.ListAccessApprovalRequestsResponse() + ) + await client.list_access_approval_requests(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_access_approval_requests_flattened(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_approval_requests), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + access_approval_requests.ListAccessApprovalRequestsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_access_approval_requests( + 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_access_approval_requests_flattened_error(): + client = CloudControlsPartnerCoreClient( + 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_access_approval_requests( + access_approval_requests.ListAccessApprovalRequestsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_access_approval_requests_flattened_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_approval_requests), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + access_approval_requests.ListAccessApprovalRequestsResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + access_approval_requests.ListAccessApprovalRequestsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_access_approval_requests( + 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_access_approval_requests_flattened_error_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_access_approval_requests( + access_approval_requests.ListAccessApprovalRequestsRequest(), + parent="parent_value", + ) + + +def test_list_access_approval_requests_pager(transport_name: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_access_approval_requests), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="abc", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[], + next_page_token="def", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="ghi", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_access_approval_requests(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, access_approval_requests.AccessApprovalRequest) + for i in results + ) + + +def test_list_access_approval_requests_pages(transport_name: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_access_approval_requests), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="abc", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[], + next_page_token="def", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="ghi", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + ), + RuntimeError, + ) + pages = list(client.list_access_approval_requests(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_access_approval_requests_async_pager(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_approval_requests), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="abc", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[], + next_page_token="def", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="ghi", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_access_approval_requests( + 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, access_approval_requests.AccessApprovalRequest) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_access_approval_requests_async_pages(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_approval_requests), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="abc", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[], + next_page_token="def", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="ghi", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + ), + 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_access_approval_requests(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", + [ + partners.GetPartnerRequest, + dict, + ], +) +def test_get_partner(request_type, transport: str = "grpc"): + client = CloudControlsPartnerCoreClient( + 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_partner), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = partners.Partner( + name="name_value", + operated_cloud_regions=["operated_cloud_regions_value"], + partner_project_id="partner_project_id_value", + ) + response = client.get_partner(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == partners.GetPartnerRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, partners.Partner) + assert response.name == "name_value" + assert response.operated_cloud_regions == ["operated_cloud_regions_value"] + assert response.partner_project_id == "partner_project_id_value" + + +def test_get_partner_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_partner), "__call__") as call: + client.get_partner() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == partners.GetPartnerRequest() + + +@pytest.mark.asyncio +async def test_get_partner_async( + transport: str = "grpc_asyncio", request_type=partners.GetPartnerRequest +): + client = CloudControlsPartnerCoreAsyncClient( + 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_partner), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + partners.Partner( + name="name_value", + operated_cloud_regions=["operated_cloud_regions_value"], + partner_project_id="partner_project_id_value", + ) + ) + response = await client.get_partner(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == partners.GetPartnerRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, partners.Partner) + assert response.name == "name_value" + assert response.operated_cloud_regions == ["operated_cloud_regions_value"] + assert response.partner_project_id == "partner_project_id_value" + + +@pytest.mark.asyncio +async def test_get_partner_async_from_dict(): + await test_get_partner_async(request_type=dict) + + +def test_get_partner_field_headers(): + client = CloudControlsPartnerCoreClient( + 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 = partners.GetPartnerRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_partner), "__call__") as call: + call.return_value = partners.Partner() + client.get_partner(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_partner_field_headers_async(): + client = CloudControlsPartnerCoreAsyncClient( + 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 = partners.GetPartnerRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_partner), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(partners.Partner()) + await client.get_partner(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_partner_flattened(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_partner), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = partners.Partner() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_partner( + 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_partner_flattened_error(): + client = CloudControlsPartnerCoreClient( + 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_partner( + partners.GetPartnerRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_partner_flattened_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_partner), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = partners.Partner() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(partners.Partner()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_partner( + 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_partner_flattened_error_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_partner( + partners.GetPartnerRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + customer_workloads.GetWorkloadRequest, + dict, + ], +) +def test_get_workload_rest(request_type): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/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 = customer_workloads.Workload( + name="name_value", + folder_id=936, + folder="folder_value", + is_onboarded=True, + key_management_project_id="key_management_project_id_value", + location="location_value", + partner=customer_workloads.Workload.Partner.PARTNER_LOCAL_CONTROLS_BY_S3NS, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = customer_workloads.Workload.pb(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_workload(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, customer_workloads.Workload) + assert response.name == "name_value" + assert response.folder_id == 936 + assert response.folder == "folder_value" + assert response.is_onboarded is True + assert response.key_management_project_id == "key_management_project_id_value" + assert response.location == "location_value" + assert ( + response.partner + == customer_workloads.Workload.Partner.PARTNER_LOCAL_CONTROLS_BY_S3NS + ) + + +def test_get_workload_rest_required_fields( + request_type=customer_workloads.GetWorkloadRequest, +): + transport_class = transports.CloudControlsPartnerCoreRestTransport + + 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_workload._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_workload._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 = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = customer_workloads.Workload() + # 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 = customer_workloads.Workload.pb(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_workload(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_workload_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_workload._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_workload_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerCoreRestInterceptor(), + ) + client = CloudControlsPartnerCoreClient(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.CloudControlsPartnerCoreRestInterceptor, "post_get_workload" + ) as post, mock.patch.object( + transports.CloudControlsPartnerCoreRestInterceptor, "pre_get_workload" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = customer_workloads.GetWorkloadRequest.pb( + customer_workloads.GetWorkloadRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = customer_workloads.Workload.to_json( + customer_workloads.Workload() + ) + + request = customer_workloads.GetWorkloadRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = customer_workloads.Workload() + + client.get_workload( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_workload_rest_bad_request( + transport: str = "rest", request_type=customer_workloads.GetWorkloadRequest +): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_workload(request) + + +def test_get_workload_rest_flattened(): + client = CloudControlsPartnerCoreClient( + 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 = customer_workloads.Workload() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4" + } + + # 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 = customer_workloads.Workload.pb(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_workload(**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=organizations/*/locations/*/customers/*/workloads/*}" + % client.transport._host, + args[1], + ) + + +def test_get_workload_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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_workload( + customer_workloads.GetWorkloadRequest(), + name="name_value", + ) + + +def test_get_workload_rest_error(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + customer_workloads.ListWorkloadsRequest, + dict, + ], +) +def test_list_workloads_rest(request_type): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "organizations/sample1/locations/sample2/customers/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 = customer_workloads.ListWorkloadsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = customer_workloads.ListWorkloadsResponse.pb(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_workloads(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListWorkloadsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_workloads_rest_required_fields( + request_type=customer_workloads.ListWorkloadsRequest, +): + transport_class = transports.CloudControlsPartnerCoreRestTransport + + 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_workloads._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_workloads._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 = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = customer_workloads.ListWorkloadsResponse() + # 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 = customer_workloads.ListWorkloadsResponse.pb(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_workloads(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_workloads_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_workloads._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_workloads_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerCoreRestInterceptor(), + ) + client = CloudControlsPartnerCoreClient(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.CloudControlsPartnerCoreRestInterceptor, "post_list_workloads" + ) as post, mock.patch.object( + transports.CloudControlsPartnerCoreRestInterceptor, "pre_list_workloads" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = customer_workloads.ListWorkloadsRequest.pb( + customer_workloads.ListWorkloadsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = customer_workloads.ListWorkloadsResponse.to_json( + customer_workloads.ListWorkloadsResponse() + ) + + request = customer_workloads.ListWorkloadsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = customer_workloads.ListWorkloadsResponse() + + client.list_workloads( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_workloads_rest_bad_request( + transport: str = "rest", request_type=customer_workloads.ListWorkloadsRequest +): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "organizations/sample1/locations/sample2/customers/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_workloads(request) + + +def test_list_workloads_rest_flattened(): + client = CloudControlsPartnerCoreClient( + 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 = customer_workloads.ListWorkloadsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "organizations/sample1/locations/sample2/customers/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 = customer_workloads.ListWorkloadsResponse.pb(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_workloads(**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=organizations/*/locations/*/customers/*}/workloads" + % client.transport._host, + args[1], + ) + + +def test_list_workloads_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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_workloads( + customer_workloads.ListWorkloadsRequest(), + parent="parent_value", + ) + + +def test_list_workloads_rest_pager(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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 = ( + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + next_page_token="abc", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[], + next_page_token="def", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + ], + next_page_token="ghi", + ), + customer_workloads.ListWorkloadsResponse( + workloads=[ + customer_workloads.Workload(), + customer_workloads.Workload(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + customer_workloads.ListWorkloadsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "organizations/sample1/locations/sample2/customers/sample3" + } + + pager = client.list_workloads(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, customer_workloads.Workload) for i in results) + + pages = list(client.list_workloads(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + customers.GetCustomerRequest, + dict, + ], +) +def test_get_customer_rest(request_type): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/locations/sample2/customers/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 = customers.Customer( + name="name_value", + display_name="display_name_value", + is_onboarded=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = customers.Customer.pb(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_customer(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, customers.Customer) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.is_onboarded is True + + +def test_get_customer_rest_required_fields(request_type=customers.GetCustomerRequest): + transport_class = transports.CloudControlsPartnerCoreRestTransport + + 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_customer._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_customer._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 = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = customers.Customer() + # 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 = customers.Customer.pb(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_customer(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_customer_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_customer._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_customer_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerCoreRestInterceptor(), + ) + client = CloudControlsPartnerCoreClient(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.CloudControlsPartnerCoreRestInterceptor, "post_get_customer" + ) as post, mock.patch.object( + transports.CloudControlsPartnerCoreRestInterceptor, "pre_get_customer" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = customers.GetCustomerRequest.pb(customers.GetCustomerRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = customers.Customer.to_json(customers.Customer()) + + request = customers.GetCustomerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = customers.Customer() + + client.get_customer( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_customer_rest_bad_request( + transport: str = "rest", request_type=customers.GetCustomerRequest +): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/locations/sample2/customers/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_customer(request) + + +def test_get_customer_rest_flattened(): + client = CloudControlsPartnerCoreClient( + 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 = customers.Customer() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/customers/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 = customers.Customer.pb(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_customer(**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=organizations/*/locations/*/customers/*}" + % client.transport._host, + args[1], + ) + + +def test_get_customer_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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_customer( + customers.GetCustomerRequest(), + name="name_value", + ) + + +def test_get_customer_rest_error(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + customers.ListCustomersRequest, + dict, + ], +) +def test_list_customers_rest(request_type): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = customers.ListCustomersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = customers.ListCustomersResponse.pb(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_customers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_customers_rest_required_fields( + request_type=customers.ListCustomersRequest, +): + transport_class = transports.CloudControlsPartnerCoreRestTransport + + 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_customers._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_customers._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 = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = customers.ListCustomersResponse() + # 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 = customers.ListCustomersResponse.pb(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_customers(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_customers_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_customers._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_customers_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerCoreRestInterceptor(), + ) + client = CloudControlsPartnerCoreClient(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.CloudControlsPartnerCoreRestInterceptor, "post_list_customers" + ) as post, mock.patch.object( + transports.CloudControlsPartnerCoreRestInterceptor, "pre_list_customers" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = customers.ListCustomersRequest.pb(customers.ListCustomersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = customers.ListCustomersResponse.to_json( + customers.ListCustomersResponse() + ) + + request = customers.ListCustomersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = customers.ListCustomersResponse() + + client.list_customers( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_customers_rest_bad_request( + transport: str = "rest", request_type=customers.ListCustomersRequest +): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_customers(request) + + +def test_list_customers_rest_flattened(): + client = CloudControlsPartnerCoreClient( + 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 = customers.ListCustomersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/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 = customers.ListCustomersResponse.pb(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_customers(**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=organizations/*/locations/*}/customers" + % client.transport._host, + args[1], + ) + + +def test_list_customers_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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_customers( + customers.ListCustomersRequest(), + parent="parent_value", + ) + + +def test_list_customers_rest_pager(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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 = ( + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + customers.Customer(), + ], + next_page_token="abc", + ), + customers.ListCustomersResponse( + customers=[], + next_page_token="def", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + ], + next_page_token="ghi", + ), + customers.ListCustomersResponse( + customers=[ + customers.Customer(), + customers.Customer(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(customers.ListCustomersResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "organizations/sample1/locations/sample2"} + + pager = client.list_customers(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, customers.Customer) for i in results) + + pages = list(client.list_customers(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + ekm_connections.GetEkmConnectionsRequest, + dict, + ], +) +def test_get_ekm_connections_rest(request_type): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/ekmConnections" + } + 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 = ekm_connections.EkmConnections( + 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 = ekm_connections.EkmConnections.pb(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_ekm_connections(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_connections.EkmConnections) + assert response.name == "name_value" + + +def test_get_ekm_connections_rest_required_fields( + request_type=ekm_connections.GetEkmConnectionsRequest, +): + transport_class = transports.CloudControlsPartnerCoreRestTransport + + 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_ekm_connections._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_ekm_connections._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 = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ekm_connections.EkmConnections() + # 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 = ekm_connections.EkmConnections.pb(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_ekm_connections(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_ekm_connections_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_ekm_connections._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_ekm_connections_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerCoreRestInterceptor(), + ) + client = CloudControlsPartnerCoreClient(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.CloudControlsPartnerCoreRestInterceptor, "post_get_ekm_connections" + ) as post, mock.patch.object( + transports.CloudControlsPartnerCoreRestInterceptor, "pre_get_ekm_connections" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ekm_connections.GetEkmConnectionsRequest.pb( + ekm_connections.GetEkmConnectionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ekm_connections.EkmConnections.to_json( + ekm_connections.EkmConnections() + ) + + request = ekm_connections.GetEkmConnectionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ekm_connections.EkmConnections() + + client.get_ekm_connections( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_ekm_connections_rest_bad_request( + transport: str = "rest", request_type=ekm_connections.GetEkmConnectionsRequest +): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/ekmConnections" + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_ekm_connections(request) + + +def test_get_ekm_connections_rest_flattened(): + client = CloudControlsPartnerCoreClient( + 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 = ekm_connections.EkmConnections() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/ekmConnections" + } + + # 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 = ekm_connections.EkmConnections.pb(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_ekm_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/v1beta/{name=organizations/*/locations/*/customers/*/workloads/*/ekmConnections}" + % client.transport._host, + args[1], + ) + + +def test_get_ekm_connections_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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_ekm_connections( + ekm_connections.GetEkmConnectionsRequest(), + name="name_value", + ) + + +def test_get_ekm_connections_rest_error(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + partner_permissions.GetPartnerPermissionsRequest, + dict, + ], +) +def test_get_partner_permissions_rest(request_type): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/partnerPermissions" + } + 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 = partner_permissions.PartnerPermissions( + name="name_value", + partner_permissions=[ + partner_permissions.PartnerPermissions.Permission.ACCESS_TRANSPARENCY_AND_EMERGENCY_ACCESS_LOGS + ], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = partner_permissions.PartnerPermissions.pb(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_partner_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, partner_permissions.PartnerPermissions) + assert response.name == "name_value" + assert response.partner_permissions == [ + partner_permissions.PartnerPermissions.Permission.ACCESS_TRANSPARENCY_AND_EMERGENCY_ACCESS_LOGS + ] + + +def test_get_partner_permissions_rest_required_fields( + request_type=partner_permissions.GetPartnerPermissionsRequest, +): + transport_class = transports.CloudControlsPartnerCoreRestTransport + + 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_partner_permissions._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_partner_permissions._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 = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = partner_permissions.PartnerPermissions() + # 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 = partner_permissions.PartnerPermissions.pb(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_partner_permissions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_partner_permissions_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_partner_permissions._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_partner_permissions_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerCoreRestInterceptor(), + ) + client = CloudControlsPartnerCoreClient(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.CloudControlsPartnerCoreRestInterceptor, + "post_get_partner_permissions", + ) as post, mock.patch.object( + transports.CloudControlsPartnerCoreRestInterceptor, + "pre_get_partner_permissions", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = partner_permissions.GetPartnerPermissionsRequest.pb( + partner_permissions.GetPartnerPermissionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = partner_permissions.PartnerPermissions.to_json( + partner_permissions.PartnerPermissions() + ) + + request = partner_permissions.GetPartnerPermissionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = partner_permissions.PartnerPermissions() + + client.get_partner_permissions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_partner_permissions_rest_bad_request( + transport: str = "rest", + request_type=partner_permissions.GetPartnerPermissionsRequest, +): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/partnerPermissions" + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_partner_permissions(request) + + +def test_get_partner_permissions_rest_flattened(): + client = CloudControlsPartnerCoreClient( + 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 = partner_permissions.PartnerPermissions() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/partnerPermissions" + } + + # 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 = partner_permissions.PartnerPermissions.pb(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_partner_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=organizations/*/locations/*/customers/*/workloads/*/partnerPermissions}" + % client.transport._host, + args[1], + ) + + +def test_get_partner_permissions_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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_partner_permissions( + partner_permissions.GetPartnerPermissionsRequest(), + name="name_value", + ) + + +def test_get_partner_permissions_rest_error(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + access_approval_requests.ListAccessApprovalRequestsRequest, + dict, + ], +) +def test_list_access_approval_requests_rest(request_type): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "organizations/sample1/locations/sample2/customers/sample3/workloads/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 = access_approval_requests.ListAccessApprovalRequestsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = access_approval_requests.ListAccessApprovalRequestsResponse.pb( + 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_access_approval_requests(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccessApprovalRequestsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_access_approval_requests_rest_required_fields( + request_type=access_approval_requests.ListAccessApprovalRequestsRequest, +): + transport_class = transports.CloudControlsPartnerCoreRestTransport + + 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_access_approval_requests._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_access_approval_requests._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 = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = access_approval_requests.ListAccessApprovalRequestsResponse() + # 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 = ( + access_approval_requests.ListAccessApprovalRequestsResponse.pb( + 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_access_approval_requests(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_access_approval_requests_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_access_approval_requests._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_access_approval_requests_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerCoreRestInterceptor(), + ) + client = CloudControlsPartnerCoreClient(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.CloudControlsPartnerCoreRestInterceptor, + "post_list_access_approval_requests", + ) as post, mock.patch.object( + transports.CloudControlsPartnerCoreRestInterceptor, + "pre_list_access_approval_requests", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = access_approval_requests.ListAccessApprovalRequestsRequest.pb( + access_approval_requests.ListAccessApprovalRequestsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + access_approval_requests.ListAccessApprovalRequestsResponse.to_json( + access_approval_requests.ListAccessApprovalRequestsResponse() + ) + ) + + request = access_approval_requests.ListAccessApprovalRequestsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + access_approval_requests.ListAccessApprovalRequestsResponse() + ) + + client.list_access_approval_requests( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_access_approval_requests_rest_bad_request( + transport: str = "rest", + request_type=access_approval_requests.ListAccessApprovalRequestsRequest, +): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "organizations/sample1/locations/sample2/customers/sample3/workloads/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_access_approval_requests(request) + + +def test_list_access_approval_requests_rest_flattened(): + client = CloudControlsPartnerCoreClient( + 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 = access_approval_requests.ListAccessApprovalRequestsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4" + } + + # 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 = access_approval_requests.ListAccessApprovalRequestsResponse.pb( + 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_access_approval_requests(**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=organizations/*/locations/*/customers/*/workloads/*}/accessApprovalRequests" + % client.transport._host, + args[1], + ) + + +def test_list_access_approval_requests_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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_access_approval_requests( + access_approval_requests.ListAccessApprovalRequestsRequest(), + parent="parent_value", + ) + + +def test_list_access_approval_requests_rest_pager(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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 = ( + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="abc", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[], + next_page_token="def", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + ], + next_page_token="ghi", + ), + access_approval_requests.ListAccessApprovalRequestsResponse( + access_approval_requests=[ + access_approval_requests.AccessApprovalRequest(), + access_approval_requests.AccessApprovalRequest(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + access_approval_requests.ListAccessApprovalRequestsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4" + } + + pager = client.list_access_approval_requests(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, access_approval_requests.AccessApprovalRequest) + for i in results + ) + + pages = list(client.list_access_approval_requests(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + partners.GetPartnerRequest, + dict, + ], +) +def test_get_partner_rest(request_type): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/locations/sample2/partner"} + 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 = partners.Partner( + name="name_value", + operated_cloud_regions=["operated_cloud_regions_value"], + partner_project_id="partner_project_id_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 = partners.Partner.pb(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_partner(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, partners.Partner) + assert response.name == "name_value" + assert response.operated_cloud_regions == ["operated_cloud_regions_value"] + assert response.partner_project_id == "partner_project_id_value" + + +def test_get_partner_rest_required_fields(request_type=partners.GetPartnerRequest): + transport_class = transports.CloudControlsPartnerCoreRestTransport + + 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_partner._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_partner._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 = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = partners.Partner() + # 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 = partners.Partner.pb(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_partner(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_partner_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_partner._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_partner_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerCoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerCoreRestInterceptor(), + ) + client = CloudControlsPartnerCoreClient(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.CloudControlsPartnerCoreRestInterceptor, "post_get_partner" + ) as post, mock.patch.object( + transports.CloudControlsPartnerCoreRestInterceptor, "pre_get_partner" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = partners.GetPartnerRequest.pb(partners.GetPartnerRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = partners.Partner.to_json(partners.Partner()) + + request = partners.GetPartnerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = partners.Partner() + + client.get_partner( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_partner_rest_bad_request( + transport: str = "rest", request_type=partners.GetPartnerRequest +): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/locations/sample2/partner"} + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_partner(request) + + +def test_get_partner_rest_flattened(): + client = CloudControlsPartnerCoreClient( + 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 = partners.Partner() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/locations/sample2/partner"} + + # 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 = partners.Partner.pb(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_partner(**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=organizations/*/locations/*/partner}" + % client.transport._host, + args[1], + ) + + +def test_get_partner_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerCoreClient( + 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_partner( + partners.GetPartnerRequest(), + name="name_value", + ) + + +def test_get_partner_rest_error(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CloudControlsPartnerCoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CloudControlsPartnerCoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudControlsPartnerCoreClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CloudControlsPartnerCoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CloudControlsPartnerCoreClient( + 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 = CloudControlsPartnerCoreClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CloudControlsPartnerCoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudControlsPartnerCoreClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudControlsPartnerCoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CloudControlsPartnerCoreClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudControlsPartnerCoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CloudControlsPartnerCoreGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerCoreGrpcTransport, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + transports.CloudControlsPartnerCoreRestTransport, + ], +) +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() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = CloudControlsPartnerCoreClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CloudControlsPartnerCoreGrpcTransport, + ) + + +def test_cloud_controls_partner_core_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CloudControlsPartnerCoreTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_cloud_controls_partner_core_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.transports.CloudControlsPartnerCoreTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.CloudControlsPartnerCoreTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_workload", + "list_workloads", + "get_customer", + "list_customers", + "get_ekm_connections", + "get_partner_permissions", + "list_access_approval_requests", + "get_partner", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_cloud_controls_partner_core_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.transports.CloudControlsPartnerCoreTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudControlsPartnerCoreTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_cloud_controls_partner_core_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_core.transports.CloudControlsPartnerCoreTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudControlsPartnerCoreTransport() + adc.assert_called_once() + + +def test_cloud_controls_partner_core_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CloudControlsPartnerCoreClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerCoreGrpcTransport, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + ], +) +def test_cloud_controls_partner_core_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerCoreGrpcTransport, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + transports.CloudControlsPartnerCoreRestTransport, + ], +) +def test_cloud_controls_partner_core_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudControlsPartnerCoreGrpcTransport, grpc_helpers), + (transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_cloud_controls_partner_core_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudcontrolspartner.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="cloudcontrolspartner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerCoreGrpcTransport, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + ], +) +def test_cloud_controls_partner_core_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_cloud_controls_partner_core_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.CloudControlsPartnerCoreRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_cloud_controls_partner_core_host_no_port(transport_name): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudcontrolspartner.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudcontrolspartner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudcontrolspartner.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_cloud_controls_partner_core_host_with_port(transport_name): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudcontrolspartner.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudcontrolspartner.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudcontrolspartner.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_cloud_controls_partner_core_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CloudControlsPartnerCoreClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CloudControlsPartnerCoreClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_workload._session + session2 = client2.transport.get_workload._session + assert session1 != session2 + session1 = client1.transport.list_workloads._session + session2 = client2.transport.list_workloads._session + assert session1 != session2 + session1 = client1.transport.get_customer._session + session2 = client2.transport.get_customer._session + assert session1 != session2 + session1 = client1.transport.list_customers._session + session2 = client2.transport.list_customers._session + assert session1 != session2 + session1 = client1.transport.get_ekm_connections._session + session2 = client2.transport.get_ekm_connections._session + assert session1 != session2 + session1 = client1.transport.get_partner_permissions._session + session2 = client2.transport.get_partner_permissions._session + assert session1 != session2 + session1 = client1.transport.list_access_approval_requests._session + session2 = client2.transport.list_access_approval_requests._session + assert session1 != session2 + session1 = client1.transport.get_partner._session + session2 = client2.transport.get_partner._session + assert session1 != session2 + + +def test_cloud_controls_partner_core_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudControlsPartnerCoreGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_cloud_controls_partner_core_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudControlsPartnerCoreGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerCoreGrpcTransport, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + ], +) +def test_cloud_controls_partner_core_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerCoreGrpcTransport, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + ], +) +def test_cloud_controls_partner_core_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_access_approval_request_path(): + organization = "squid" + location = "clam" + customer = "whelk" + workload = "octopus" + access_approval_request = "oyster" + expected = "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/accessApprovalRequests/{access_approval_request}".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + access_approval_request=access_approval_request, + ) + actual = CloudControlsPartnerCoreClient.access_approval_request_path( + organization, location, customer, workload, access_approval_request + ) + assert expected == actual + + +def test_parse_access_approval_request_path(): + expected = { + "organization": "nudibranch", + "location": "cuttlefish", + "customer": "mussel", + "workload": "winkle", + "access_approval_request": "nautilus", + } + path = CloudControlsPartnerCoreClient.access_approval_request_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_access_approval_request_path(path) + assert expected == actual + + +def test_customer_path(): + organization = "scallop" + location = "abalone" + customer = "squid" + expected = ( + "organizations/{organization}/locations/{location}/customers/{customer}".format( + organization=organization, + location=location, + customer=customer, + ) + ) + actual = CloudControlsPartnerCoreClient.customer_path( + organization, location, customer + ) + assert expected == actual + + +def test_parse_customer_path(): + expected = { + "organization": "clam", + "location": "whelk", + "customer": "octopus", + } + path = CloudControlsPartnerCoreClient.customer_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_customer_path(path) + assert expected == actual + + +def test_ekm_connections_path(): + organization = "oyster" + location = "nudibranch" + customer = "cuttlefish" + workload = "mussel" + expected = "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/ekmConnections".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + ) + actual = CloudControlsPartnerCoreClient.ekm_connections_path( + organization, location, customer, workload + ) + assert expected == actual + + +def test_parse_ekm_connections_path(): + expected = { + "organization": "winkle", + "location": "nautilus", + "customer": "scallop", + "workload": "abalone", + } + path = CloudControlsPartnerCoreClient.ekm_connections_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_ekm_connections_path(path) + assert expected == actual + + +def test_partner_path(): + organization = "squid" + location = "clam" + expected = "organizations/{organization}/locations/{location}/partner".format( + organization=organization, + location=location, + ) + actual = CloudControlsPartnerCoreClient.partner_path(organization, location) + assert expected == actual + + +def test_parse_partner_path(): + expected = { + "organization": "whelk", + "location": "octopus", + } + path = CloudControlsPartnerCoreClient.partner_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_partner_path(path) + assert expected == actual + + +def test_partner_permissions_path(): + organization = "oyster" + location = "nudibranch" + customer = "cuttlefish" + workload = "mussel" + expected = "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/partnerPermissions".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + ) + actual = CloudControlsPartnerCoreClient.partner_permissions_path( + organization, location, customer, workload + ) + assert expected == actual + + +def test_parse_partner_permissions_path(): + expected = { + "organization": "winkle", + "location": "nautilus", + "customer": "scallop", + "workload": "abalone", + } + path = CloudControlsPartnerCoreClient.partner_permissions_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_partner_permissions_path(path) + assert expected == actual + + +def test_workload_path(): + organization = "squid" + location = "clam" + customer = "whelk" + workload = "octopus" + expected = "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + ) + actual = CloudControlsPartnerCoreClient.workload_path( + organization, location, customer, workload + ) + assert expected == actual + + +def test_parse_workload_path(): + expected = { + "organization": "oyster", + "location": "nudibranch", + "customer": "cuttlefish", + "workload": "mussel", + } + path = CloudControlsPartnerCoreClient.workload_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_workload_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = CloudControlsPartnerCoreClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = CloudControlsPartnerCoreClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = CloudControlsPartnerCoreClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = CloudControlsPartnerCoreClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = CloudControlsPartnerCoreClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = CloudControlsPartnerCoreClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format( + project=project, + ) + actual = CloudControlsPartnerCoreClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = CloudControlsPartnerCoreClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = CloudControlsPartnerCoreClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = CloudControlsPartnerCoreClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerCoreClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.CloudControlsPartnerCoreTransport, "_prep_wrapped_messages" + ) as prep: + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.CloudControlsPartnerCoreTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = CloudControlsPartnerCoreClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CloudControlsPartnerCoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = CloudControlsPartnerCoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + CloudControlsPartnerCoreClient, + transports.CloudControlsPartnerCoreGrpcTransport, + ), + ( + CloudControlsPartnerCoreAsyncClient, + transports.CloudControlsPartnerCoreGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-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 new file mode 100644 index 000000000000..7d2056c0f0cf --- /dev/null +++ b/packages/google-cloud-cloudcontrolspartner/tests/unit/gapic/cloudcontrolspartner_v1beta/test_cloud_controls_partner_monitoring.py @@ -0,0 +1,3327 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import Iterable +import json +import math + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import json_format +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import interval_pb2 # type: ignore +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +from google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_monitoring import ( + CloudControlsPartnerMonitoringAsyncClient, + CloudControlsPartnerMonitoringClient, + pagers, + transports, +) +from google.cloud.cloudcontrolspartner_v1beta.types import violations + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CloudControlsPartnerMonitoringClient._get_default_mtls_endpoint(None) is None + assert ( + CloudControlsPartnerMonitoringClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + CloudControlsPartnerMonitoringClient._get_default_mtls_endpoint( + api_mtls_endpoint + ) + == api_mtls_endpoint + ) + assert ( + CloudControlsPartnerMonitoringClient._get_default_mtls_endpoint( + sandbox_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + CloudControlsPartnerMonitoringClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + CloudControlsPartnerMonitoringClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert CloudControlsPartnerMonitoringClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert CloudControlsPartnerMonitoringClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert CloudControlsPartnerMonitoringClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + CloudControlsPartnerMonitoringClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert CloudControlsPartnerMonitoringClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert CloudControlsPartnerMonitoringClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert CloudControlsPartnerMonitoringClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + CloudControlsPartnerMonitoringClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert CloudControlsPartnerMonitoringClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert ( + CloudControlsPartnerMonitoringClient._get_client_cert_source(None, False) + is None + ) + assert ( + CloudControlsPartnerMonitoringClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + CloudControlsPartnerMonitoringClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + CloudControlsPartnerMonitoringClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + CloudControlsPartnerMonitoringClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + CloudControlsPartnerMonitoringClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerMonitoringClient), +) +@mock.patch.object( + CloudControlsPartnerMonitoringAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerMonitoringAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = CloudControlsPartnerMonitoringClient._DEFAULT_UNIVERSE + default_endpoint = ( + CloudControlsPartnerMonitoringClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = ( + CloudControlsPartnerMonitoringClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + ) + + assert ( + CloudControlsPartnerMonitoringClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + CloudControlsPartnerMonitoringClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == CloudControlsPartnerMonitoringClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + CloudControlsPartnerMonitoringClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + CloudControlsPartnerMonitoringClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == CloudControlsPartnerMonitoringClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + CloudControlsPartnerMonitoringClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == CloudControlsPartnerMonitoringClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + CloudControlsPartnerMonitoringClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + CloudControlsPartnerMonitoringClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + CloudControlsPartnerMonitoringClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + CloudControlsPartnerMonitoringClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + CloudControlsPartnerMonitoringClient._get_universe_domain( + None, universe_domain_env + ) + == universe_domain_env + ) + assert ( + CloudControlsPartnerMonitoringClient._get_universe_domain(None, None) + == CloudControlsPartnerMonitoringClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + CloudControlsPartnerMonitoringClient._get_universe_domain("", None) + 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", + [ + (CloudControlsPartnerMonitoringClient, "grpc"), + (CloudControlsPartnerMonitoringAsyncClient, "grpc_asyncio"), + (CloudControlsPartnerMonitoringClient, "rest"), + ], +) +def test_cloud_controls_partner_monitoring_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "cloudcontrolspartner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudcontrolspartner.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.CloudControlsPartnerMonitoringGrpcTransport, "grpc"), + (transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.CloudControlsPartnerMonitoringRestTransport, "rest"), + ], +) +def test_cloud_controls_partner_monitoring_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (CloudControlsPartnerMonitoringClient, "grpc"), + (CloudControlsPartnerMonitoringAsyncClient, "grpc_asyncio"), + (CloudControlsPartnerMonitoringClient, "rest"), + ], +) +def test_cloud_controls_partner_monitoring_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "cloudcontrolspartner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudcontrolspartner.googleapis.com" + ) + + +def test_cloud_controls_partner_monitoring_client_get_transport_class(): + transport = CloudControlsPartnerMonitoringClient.get_transport_class() + available_transports = [ + transports.CloudControlsPartnerMonitoringGrpcTransport, + transports.CloudControlsPartnerMonitoringRestTransport, + ] + assert transport in available_transports + + transport = CloudControlsPartnerMonitoringClient.get_transport_class("grpc") + assert transport == transports.CloudControlsPartnerMonitoringGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringGrpcTransport, + "grpc", + ), + ( + CloudControlsPartnerMonitoringAsyncClient, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + CloudControlsPartnerMonitoringClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerMonitoringClient), +) +@mock.patch.object( + CloudControlsPartnerMonitoringAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerMonitoringAsyncClient), +) +def test_cloud_controls_partner_monitoring_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object( + CloudControlsPartnerMonitoringClient, "get_transport_class" + ) as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object( + CloudControlsPartnerMonitoringClient, "get_transport_class" + ) as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringGrpcTransport, + "grpc", + "true", + ), + ( + CloudControlsPartnerMonitoringAsyncClient, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringGrpcTransport, + "grpc", + "false", + ), + ( + CloudControlsPartnerMonitoringAsyncClient, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringRestTransport, + "rest", + "true", + ), + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + CloudControlsPartnerMonitoringClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerMonitoringClient), +) +@mock.patch.object( + CloudControlsPartnerMonitoringAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerMonitoringAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_cloud_controls_partner_monitoring_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", + [CloudControlsPartnerMonitoringClient, CloudControlsPartnerMonitoringAsyncClient], +) +@mock.patch.object( + CloudControlsPartnerMonitoringClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudControlsPartnerMonitoringClient), +) +@mock.patch.object( + CloudControlsPartnerMonitoringAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CloudControlsPartnerMonitoringAsyncClient), +) +def test_cloud_controls_partner_monitoring_client_get_mtls_endpoint_and_cert_source( + client_class, +): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize( + "client_class", + [CloudControlsPartnerMonitoringClient, CloudControlsPartnerMonitoringAsyncClient], +) +@mock.patch.object( + CloudControlsPartnerMonitoringClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerMonitoringClient), +) +@mock.patch.object( + CloudControlsPartnerMonitoringAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CloudControlsPartnerMonitoringAsyncClient), +) +def test_cloud_controls_partner_monitoring_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = CloudControlsPartnerMonitoringClient._DEFAULT_UNIVERSE + default_endpoint = ( + CloudControlsPartnerMonitoringClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = ( + CloudControlsPartnerMonitoringClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringGrpcTransport, + "grpc", + ), + ( + CloudControlsPartnerMonitoringAsyncClient, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringRestTransport, + "rest", + ), + ], +) +def test_cloud_controls_partner_monitoring_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + CloudControlsPartnerMonitoringAsyncClient, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringRestTransport, + "rest", + None, + ), + ], +) +def test_cloud_controls_partner_monitoring_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_cloud_controls_partner_monitoring_client_client_options_from_dict(): + with mock.patch( + "google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_monitoring.transports.CloudControlsPartnerMonitoringGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = CloudControlsPartnerMonitoringClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + CloudControlsPartnerMonitoringAsyncClient, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_cloud_controls_partner_monitoring_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudcontrolspartner.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="cloudcontrolspartner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + violations.ListViolationsRequest, + dict, + ], +) +def test_list_violations(request_type, transport: str = "grpc"): + client = CloudControlsPartnerMonitoringClient( + 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_violations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = violations.ListViolationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_violations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == violations.ListViolationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListViolationsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_violations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_violations), "__call__") as call: + client.list_violations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == violations.ListViolationsRequest() + + +@pytest.mark.asyncio +async def test_list_violations_async( + transport: str = "grpc_asyncio", request_type=violations.ListViolationsRequest +): + client = CloudControlsPartnerMonitoringAsyncClient( + 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_violations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + violations.ListViolationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_violations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == violations.ListViolationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListViolationsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_violations_async_from_dict(): + await test_list_violations_async(request_type=dict) + + +def test_list_violations_field_headers(): + client = CloudControlsPartnerMonitoringClient( + 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 = violations.ListViolationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_violations), "__call__") as call: + call.return_value = violations.ListViolationsResponse() + client.list_violations(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_violations_field_headers_async(): + client = CloudControlsPartnerMonitoringAsyncClient( + 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 = violations.ListViolationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_violations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + violations.ListViolationsResponse() + ) + await client.list_violations(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_violations_flattened(): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_violations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = violations.ListViolationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_violations( + 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_violations_flattened_error(): + client = CloudControlsPartnerMonitoringClient( + 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_violations( + violations.ListViolationsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_violations_flattened_async(): + client = CloudControlsPartnerMonitoringAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_violations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = violations.ListViolationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + violations.ListViolationsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_violations( + 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_violations_flattened_error_async(): + client = CloudControlsPartnerMonitoringAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_violations( + violations.ListViolationsRequest(), + parent="parent_value", + ) + + +def test_list_violations_pager(transport_name: str = "grpc"): + client = CloudControlsPartnerMonitoringClient( + 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_violations), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + violations.Violation(), + ], + next_page_token="abc", + ), + violations.ListViolationsResponse( + violations=[], + next_page_token="def", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + ], + next_page_token="ghi", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_violations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, violations.Violation) for i in results) + + +def test_list_violations_pages(transport_name: str = "grpc"): + client = CloudControlsPartnerMonitoringClient( + 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_violations), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + violations.Violation(), + ], + next_page_token="abc", + ), + violations.ListViolationsResponse( + violations=[], + next_page_token="def", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + ], + next_page_token="ghi", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_violations(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_violations_async_pager(): + client = CloudControlsPartnerMonitoringAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_violations), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + violations.Violation(), + ], + next_page_token="abc", + ), + violations.ListViolationsResponse( + violations=[], + next_page_token="def", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + ], + next_page_token="ghi", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_violations( + 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, violations.Violation) for i in responses) + + +@pytest.mark.asyncio +async def test_list_violations_async_pages(): + client = CloudControlsPartnerMonitoringAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_violations), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + violations.Violation(), + ], + next_page_token="abc", + ), + violations.ListViolationsResponse( + violations=[], + next_page_token="def", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + ], + next_page_token="ghi", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + ], + ), + 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_violations(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", + [ + violations.GetViolationRequest, + dict, + ], +) +def test_get_violation(request_type, transport: str = "grpc"): + client = CloudControlsPartnerMonitoringClient( + 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_violation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = violations.Violation( + name="name_value", + description="description_value", + category="category_value", + state=violations.Violation.State.RESOLVED, + non_compliant_org_policy="non_compliant_org_policy_value", + folder_id=936, + ) + response = client.get_violation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == violations.GetViolationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, violations.Violation) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.category == "category_value" + assert response.state == violations.Violation.State.RESOLVED + assert response.non_compliant_org_policy == "non_compliant_org_policy_value" + assert response.folder_id == 936 + + +def test_get_violation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_violation), "__call__") as call: + client.get_violation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == violations.GetViolationRequest() + + +@pytest.mark.asyncio +async def test_get_violation_async( + transport: str = "grpc_asyncio", request_type=violations.GetViolationRequest +): + client = CloudControlsPartnerMonitoringAsyncClient( + 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_violation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + violations.Violation( + name="name_value", + description="description_value", + category="category_value", + state=violations.Violation.State.RESOLVED, + non_compliant_org_policy="non_compliant_org_policy_value", + folder_id=936, + ) + ) + response = await client.get_violation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == violations.GetViolationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, violations.Violation) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.category == "category_value" + assert response.state == violations.Violation.State.RESOLVED + assert response.non_compliant_org_policy == "non_compliant_org_policy_value" + assert response.folder_id == 936 + + +@pytest.mark.asyncio +async def test_get_violation_async_from_dict(): + await test_get_violation_async(request_type=dict) + + +def test_get_violation_field_headers(): + client = CloudControlsPartnerMonitoringClient( + 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 = violations.GetViolationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_violation), "__call__") as call: + call.return_value = violations.Violation() + client.get_violation(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_violation_field_headers_async(): + client = CloudControlsPartnerMonitoringAsyncClient( + 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 = violations.GetViolationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_violation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + violations.Violation() + ) + await client.get_violation(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_violation_flattened(): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_violation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = violations.Violation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_violation( + 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_violation_flattened_error(): + client = CloudControlsPartnerMonitoringClient( + 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_violation( + violations.GetViolationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_violation_flattened_async(): + client = CloudControlsPartnerMonitoringAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_violation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = violations.Violation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + violations.Violation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_violation( + 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_violation_flattened_error_async(): + client = CloudControlsPartnerMonitoringAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_violation( + violations.GetViolationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + violations.ListViolationsRequest, + dict, + ], +) +def test_list_violations_rest(request_type): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "organizations/sample1/locations/sample2/customers/sample3/workloads/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 = violations.ListViolationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = violations.ListViolationsResponse.pb(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_violations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListViolationsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_violations_rest_required_fields( + request_type=violations.ListViolationsRequest, +): + transport_class = transports.CloudControlsPartnerMonitoringRestTransport + + 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_violations._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_violations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "interval", + "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 = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = violations.ListViolationsResponse() + # 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 = violations.ListViolationsResponse.pb(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_violations(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_violations_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerMonitoringRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_violations._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "interval", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_violations_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerMonitoringRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerMonitoringRestInterceptor(), + ) + client = CloudControlsPartnerMonitoringClient(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.CloudControlsPartnerMonitoringRestInterceptor, "post_list_violations" + ) as post, mock.patch.object( + transports.CloudControlsPartnerMonitoringRestInterceptor, "pre_list_violations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = violations.ListViolationsRequest.pb( + violations.ListViolationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = violations.ListViolationsResponse.to_json( + violations.ListViolationsResponse() + ) + + request = violations.ListViolationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = violations.ListViolationsResponse() + + client.list_violations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_violations_rest_bad_request( + transport: str = "rest", request_type=violations.ListViolationsRequest +): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "organizations/sample1/locations/sample2/customers/sample3/workloads/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_violations(request) + + +def test_list_violations_rest_flattened(): + client = CloudControlsPartnerMonitoringClient( + 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 = violations.ListViolationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4" + } + + # 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 = violations.ListViolationsResponse.pb(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_violations(**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=organizations/*/locations/*/customers/*/workloads/*}/violations" + % client.transport._host, + args[1], + ) + + +def test_list_violations_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerMonitoringClient( + 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_violations( + violations.ListViolationsRequest(), + parent="parent_value", + ) + + +def test_list_violations_rest_pager(transport: str = "rest"): + client = CloudControlsPartnerMonitoringClient( + 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 = ( + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + violations.Violation(), + ], + next_page_token="abc", + ), + violations.ListViolationsResponse( + violations=[], + next_page_token="def", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + ], + next_page_token="ghi", + ), + violations.ListViolationsResponse( + violations=[ + violations.Violation(), + violations.Violation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(violations.ListViolationsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4" + } + + pager = client.list_violations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, violations.Violation) for i in results) + + pages = list(client.list_violations(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + violations.GetViolationRequest, + dict, + ], +) +def test_get_violation_rest(request_type): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/violations/sample5" + } + 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 = violations.Violation( + name="name_value", + description="description_value", + category="category_value", + state=violations.Violation.State.RESOLVED, + non_compliant_org_policy="non_compliant_org_policy_value", + folder_id=936, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = violations.Violation.pb(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_violation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, violations.Violation) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.category == "category_value" + assert response.state == violations.Violation.State.RESOLVED + assert response.non_compliant_org_policy == "non_compliant_org_policy_value" + assert response.folder_id == 936 + + +def test_get_violation_rest_required_fields( + request_type=violations.GetViolationRequest, +): + transport_class = transports.CloudControlsPartnerMonitoringRestTransport + + 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_violation._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_violation._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 = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = violations.Violation() + # 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 = violations.Violation.pb(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_violation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_violation_rest_unset_required_fields(): + transport = transports.CloudControlsPartnerMonitoringRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_violation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_violation_rest_interceptors(null_interceptor): + transport = transports.CloudControlsPartnerMonitoringRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudControlsPartnerMonitoringRestInterceptor(), + ) + client = CloudControlsPartnerMonitoringClient(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.CloudControlsPartnerMonitoringRestInterceptor, "post_get_violation" + ) as post, mock.patch.object( + transports.CloudControlsPartnerMonitoringRestInterceptor, "pre_get_violation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = violations.GetViolationRequest.pb(violations.GetViolationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = violations.Violation.to_json(violations.Violation()) + + request = violations.GetViolationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = violations.Violation() + + client.get_violation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_violation_rest_bad_request( + transport: str = "rest", request_type=violations.GetViolationRequest +): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/violations/sample5" + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_violation(request) + + +def test_get_violation_rest_flattened(): + client = CloudControlsPartnerMonitoringClient( + 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 = violations.Violation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/customers/sample3/workloads/sample4/violations/sample5" + } + + # 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 = violations.Violation.pb(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_violation(**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=organizations/*/locations/*/customers/*/workloads/*/violations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_violation_rest_flattened_error(transport: str = "rest"): + client = CloudControlsPartnerMonitoringClient( + 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_violation( + violations.GetViolationRequest(), + name="name_value", + ) + + +def test_get_violation_rest_error(): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CloudControlsPartnerMonitoringGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CloudControlsPartnerMonitoringGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudControlsPartnerMonitoringClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CloudControlsPartnerMonitoringGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CloudControlsPartnerMonitoringClient( + 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 = CloudControlsPartnerMonitoringClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CloudControlsPartnerMonitoringGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudControlsPartnerMonitoringClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudControlsPartnerMonitoringGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CloudControlsPartnerMonitoringClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudControlsPartnerMonitoringGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerMonitoringGrpcTransport, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + transports.CloudControlsPartnerMonitoringRestTransport, + ], +) +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() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = CloudControlsPartnerMonitoringClient.get_transport_class( + transport_name + )( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CloudControlsPartnerMonitoringGrpcTransport, + ) + + +def test_cloud_controls_partner_monitoring_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CloudControlsPartnerMonitoringTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_cloud_controls_partner_monitoring_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_monitoring.transports.CloudControlsPartnerMonitoringTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.CloudControlsPartnerMonitoringTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_violations", + "get_violation", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_cloud_controls_partner_monitoring_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_monitoring.transports.CloudControlsPartnerMonitoringTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudControlsPartnerMonitoringTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_cloud_controls_partner_monitoring_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.cloudcontrolspartner_v1beta.services.cloud_controls_partner_monitoring.transports.CloudControlsPartnerMonitoringTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudControlsPartnerMonitoringTransport() + adc.assert_called_once() + + +def test_cloud_controls_partner_monitoring_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + CloudControlsPartnerMonitoringClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerMonitoringGrpcTransport, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + ], +) +def test_cloud_controls_partner_monitoring_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerMonitoringGrpcTransport, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + transports.CloudControlsPartnerMonitoringRestTransport, + ], +) +def test_cloud_controls_partner_monitoring_transport_auth_gdch_credentials( + transport_class, +): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.CloudControlsPartnerMonitoringGrpcTransport, grpc_helpers), + ( + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + grpc_helpers_async, + ), + ], +) +def test_cloud_controls_partner_monitoring_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudcontrolspartner.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="cloudcontrolspartner.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerMonitoringGrpcTransport, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + ], +) +def test_cloud_controls_partner_monitoring_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_cloud_controls_partner_monitoring_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.CloudControlsPartnerMonitoringRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_cloud_controls_partner_monitoring_host_no_port(transport_name): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudcontrolspartner.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudcontrolspartner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudcontrolspartner.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_cloud_controls_partner_monitoring_host_with_port(transport_name): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudcontrolspartner.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudcontrolspartner.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudcontrolspartner.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_cloud_controls_partner_monitoring_client_transport_session_collision( + transport_name, +): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CloudControlsPartnerMonitoringClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CloudControlsPartnerMonitoringClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_violations._session + session2 = client2.transport.list_violations._session + assert session1 != session2 + session1 = client1.transport.get_violation._session + session2 = client2.transport.get_violation._session + assert session1 != session2 + + +def test_cloud_controls_partner_monitoring_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudControlsPartnerMonitoringGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_cloud_controls_partner_monitoring_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerMonitoringGrpcTransport, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + ], +) +def test_cloud_controls_partner_monitoring_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudControlsPartnerMonitoringGrpcTransport, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + ], +) +def test_cloud_controls_partner_monitoring_transport_channel_mtls_with_adc( + transport_class, +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_violation_path(): + organization = "squid" + location = "clam" + customer = "whelk" + workload = "octopus" + violation = "oyster" + expected = "organizations/{organization}/locations/{location}/customers/{customer}/workloads/{workload}/violations/{violation}".format( + organization=organization, + location=location, + customer=customer, + workload=workload, + violation=violation, + ) + actual = CloudControlsPartnerMonitoringClient.violation_path( + organization, location, customer, workload, violation + ) + assert expected == actual + + +def test_parse_violation_path(): + expected = { + "organization": "nudibranch", + "location": "cuttlefish", + "customer": "mussel", + "workload": "winkle", + "violation": "nautilus", + } + path = CloudControlsPartnerMonitoringClient.violation_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerMonitoringClient.parse_violation_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = CloudControlsPartnerMonitoringClient.common_billing_account_path( + billing_account + ) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = CloudControlsPartnerMonitoringClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerMonitoringClient.parse_common_billing_account_path( + path + ) + assert expected == actual + + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = CloudControlsPartnerMonitoringClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = CloudControlsPartnerMonitoringClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerMonitoringClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = CloudControlsPartnerMonitoringClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = CloudControlsPartnerMonitoringClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerMonitoringClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format( + project=project, + ) + actual = CloudControlsPartnerMonitoringClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = CloudControlsPartnerMonitoringClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerMonitoringClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = CloudControlsPartnerMonitoringClient.common_location_path( + project, location + ) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = CloudControlsPartnerMonitoringClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CloudControlsPartnerMonitoringClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.CloudControlsPartnerMonitoringTransport, "_prep_wrapped_messages" + ) as prep: + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.CloudControlsPartnerMonitoringTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = CloudControlsPartnerMonitoringClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CloudControlsPartnerMonitoringAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = CloudControlsPartnerMonitoringClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + CloudControlsPartnerMonitoringClient, + transports.CloudControlsPartnerMonitoringGrpcTransport, + ), + ( + CloudControlsPartnerMonitoringAsyncClient, + transports.CloudControlsPartnerMonitoringGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-cloudquotas/CHANGELOG.md b/packages/google-cloud-cloudquotas/CHANGELOG.md index 953bbba97feb..8e3260d50544 100644 --- a/packages/google-cloud-cloudquotas/CHANGELOG.md +++ b/packages/google-cloud-cloudquotas/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.4](https://github.com/googleapis/google-cloud-python/compare/google-cloud-cloudquotas-v0.1.3...google-cloud-cloudquotas-v0.1.4) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [0.1.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-cloudquotas-v0.1.2...google-cloud-cloudquotas-v0.1.3) (2024-02-22) diff --git a/packages/google-cloud-cloudquotas/google/cloud/cloudquotas/gapic_version.py b/packages/google-cloud-cloudquotas/google/cloud/cloudquotas/gapic_version.py index 536d6648a6f0..286ce4ad5531 100644 --- a/packages/google-cloud-cloudquotas/google/cloud/cloudquotas/gapic_version.py +++ b/packages/google-cloud-cloudquotas/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.3" # {x-release-please-version} +__version__ = "0.1.4" # {x-release-please-version} diff --git a/packages/google-cloud-cloudquotas/google/cloud/cloudquotas_v1/gapic_version.py b/packages/google-cloud-cloudquotas/google/cloud/cloudquotas_v1/gapic_version.py index 536d6648a6f0..286ce4ad5531 100644 --- a/packages/google-cloud-cloudquotas/google/cloud/cloudquotas_v1/gapic_version.py +++ b/packages/google-cloud-cloudquotas/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.3" # {x-release-please-version} +__version__ = "0.1.4" # {x-release-please-version} diff --git a/packages/google-cloud-cloudquotas/samples/generated_samples/snippet_metadata_google.api.cloudquotas.v1.json b/packages/google-cloud-cloudquotas/samples/generated_samples/snippet_metadata_google.api.cloudquotas.v1.json index 4f6a1c9cefba..43d96dd75e12 100644 --- a/packages/google-cloud-cloudquotas/samples/generated_samples/snippet_metadata_google.api.cloudquotas.v1.json +++ b/packages/google-cloud-cloudquotas/samples/generated_samples/snippet_metadata_google.api.cloudquotas.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-quotas", - "version": "0.1.3" + "version": "0.1.4" }, "snippets": [ { diff --git a/packages/google-cloud-cloudquotas/setup.py b/packages/google-cloud-cloudquotas/setup.py index 28168efd9a3f..c7ff074c6581 100644 --- a/packages/google-cloud-cloudquotas/setup.py +++ b/packages/google-cloud-cloudquotas/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-commerce-consumer-procurement/CHANGELOG.md b/packages/google-cloud-commerce-consumer-procurement/CHANGELOG.md index 48dfa9d128d7..0f41b8e9f0bf 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.5](https://github.com/googleapis/google-cloud-python/compare/google-cloud-commerce-consumer-procurement-v0.1.4...google-cloud-commerce-consumer-procurement-v0.1.5) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [0.1.4](https://github.com/googleapis/google-cloud-python/compare/google-cloud-commerce-consumer-procurement-v0.1.3...google-cloud-commerce-consumer-procurement-v0.1.4) (2024-02-22) 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 286ce4ad5531..ae12f4dfd596 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.4" # {x-release-please-version} +__version__ = "0.1.5" # {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 286ce4ad5531..ae12f4dfd596 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.4" # {x-release-please-version} +__version__ = "0.1.5" # {x-release-please-version} 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 286ce4ad5531..ae12f4dfd596 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.4" # {x-release-please-version} +__version__ = "0.1.5" # {x-release-please-version} 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 171c5ef80321..8ce042cca684 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.4" + "version": "0.1.5" }, "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 7539e656da9e..9cee1e33ac54 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.4" + "version": "0.1.5" }, "snippets": [ { diff --git a/packages/google-cloud-commerce-consumer-procurement/setup.py b/packages/google-cloud-commerce-consumer-procurement/setup.py index b9b84f7124ea..c4949271c191 100644 --- a/packages/google-cloud-commerce-consumer-procurement/setup.py +++ b/packages/google-cloud-commerce-consumer-procurement/setup.py @@ -44,7 +44,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-common/CHANGELOG.md b/packages/google-cloud-common/CHANGELOG.md index f57ee615f68a..efcc759b172e 100644 --- a/packages/google-cloud-common/CHANGELOG.md +++ b/packages/google-cloud-common/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.3.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-common-v1.3.2...google-cloud-common-v1.3.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [1.3.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-common-v1.3.1...google-cloud-common-v1.3.2) (2024-02-22) diff --git a/packages/google-cloud-common/google/cloud/common/gapic_version.py b/packages/google-cloud-common/google/cloud/common/gapic_version.py index 7446194bbca6..f4b33bf9176f 100644 --- a/packages/google-cloud-common/google/cloud/common/gapic_version.py +++ b/packages/google-cloud-common/google/cloud/common/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.3.2" # {x-release-please-version} +__version__ = "1.3.3" # {x-release-please-version} diff --git a/packages/google-cloud-common/setup.py b/packages/google-cloud-common/setup.py index cb559a2aecfc..fd7273e7632e 100644 --- a/packages/google-cloud-common/setup.py +++ b/packages/google-cloud-common/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-compute/CHANGELOG.md b/packages/google-cloud-compute/CHANGELOG.md index f5460b1cb8ef..4eab96c6b6ec 100644 --- a/packages/google-cloud-compute/CHANGELOG.md +++ b/packages/google-cloud-compute/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## [1.18.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-compute-v1.17.0...google-cloud-compute-v1.18.0) (2024-03-05) + + +### Features + +* Update Compute Engine API to revision 20240220 ([6a32592](https://github.com/googleapis/google-cloud-python/commit/6a3259282df0f197ac42e02fe2e799ae93bcef44)) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([6a32592](https://github.com/googleapis/google-cloud-python/commit/6a3259282df0f197ac42e02fe2e799ae93bcef44)) + ## [1.17.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-compute-v1.16.1...google-cloud-compute-v1.17.0) (2024-02-22) diff --git a/packages/google-cloud-compute/docs/compute_v1/instant_snapshots.rst b/packages/google-cloud-compute/docs/compute_v1/instant_snapshots.rst new file mode 100644 index 000000000000..4e6d8c6a0aae --- /dev/null +++ b/packages/google-cloud-compute/docs/compute_v1/instant_snapshots.rst @@ -0,0 +1,10 @@ +InstantSnapshots +---------------------------------- + +.. automodule:: google.cloud.compute_v1.services.instant_snapshots + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1.services.instant_snapshots.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute/docs/compute_v1/region_instant_snapshots.rst b/packages/google-cloud-compute/docs/compute_v1/region_instant_snapshots.rst new file mode 100644 index 000000000000..1f9f298bb305 --- /dev/null +++ b/packages/google-cloud-compute/docs/compute_v1/region_instant_snapshots.rst @@ -0,0 +1,10 @@ +RegionInstantSnapshots +---------------------------------------- + +.. automodule:: google.cloud.compute_v1.services.region_instant_snapshots + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1.services.region_instant_snapshots.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute/docs/compute_v1/services_.rst b/packages/google-cloud-compute/docs/compute_v1/services_.rst index 28a6e7a0237d..afd320f55e0f 100644 --- a/packages/google-cloud-compute/docs/compute_v1/services_.rst +++ b/packages/google-cloud-compute/docs/compute_v1/services_.rst @@ -27,6 +27,7 @@ Services for Google Cloud Compute v1 API instance_groups instances instance_templates + instant_snapshots interconnect_attachments interconnect_locations interconnect_remote_locations @@ -58,6 +59,7 @@ Services for Google Cloud Compute v1 API region_instance_groups region_instances region_instance_templates + region_instant_snapshots region_network_endpoint_groups region_network_firewall_policies region_notification_endpoints diff --git a/packages/google-cloud-compute/google/cloud/compute/__init__.py b/packages/google-cloud-compute/google/cloud/compute/__init__.py index 04311406b2b1..8a33fbe92258 100644 --- a/packages/google-cloud-compute/google/cloud/compute/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute/__init__.py @@ -70,6 +70,9 @@ InstanceTemplatesClient, ) from google.cloud.compute_v1.services.instances.client import InstancesClient +from google.cloud.compute_v1.services.instant_snapshots.client import ( + InstantSnapshotsClient, +) from google.cloud.compute_v1.services.interconnect_attachments.client import ( InterconnectAttachmentsClient, ) @@ -141,6 +144,9 @@ from google.cloud.compute_v1.services.region_instances.client import ( RegionInstancesClient, ) +from google.cloud.compute_v1.services.region_instant_snapshots.client import ( + RegionInstantSnapshotsClient, +) from google.cloud.compute_v1.services.region_network_endpoint_groups.client import ( RegionNetworkEndpointGroupsClient, ) @@ -269,6 +275,7 @@ AggregatedListInstanceGroupsRequest, AggregatedListInstancesRequest, AggregatedListInstanceTemplatesRequest, + AggregatedListInstantSnapshotsRequest, AggregatedListInterconnectAttachmentsRequest, AggregatedListMachineTypesRequest, AggregatedListNetworkAttachmentsRequest, @@ -418,6 +425,7 @@ DeleteInstancesInstanceGroupManagerRequest, DeleteInstancesRegionInstanceGroupManagerRequest, DeleteInstanceTemplateRequest, + DeleteInstantSnapshotRequest, DeleteInterconnectAttachmentRequest, DeleteInterconnectRequest, DeleteLicenseRequest, @@ -442,6 +450,7 @@ DeleteRegionHealthCheckServiceRequest, DeleteRegionInstanceGroupManagerRequest, DeleteRegionInstanceTemplateRequest, + DeleteRegionInstantSnapshotRequest, DeleteRegionNetworkEndpointGroupRequest, DeleteRegionNetworkFirewallPolicyRequest, DeleteRegionNotificationEndpointRequest, @@ -581,6 +590,7 @@ GetIamPolicyImageRequest, GetIamPolicyInstanceRequest, GetIamPolicyInstanceTemplateRequest, + GetIamPolicyInstantSnapshotRequest, GetIamPolicyLicenseRequest, GetIamPolicyMachineImageRequest, GetIamPolicyNetworkAttachmentRequest, @@ -589,6 +599,7 @@ GetIamPolicyNodeTemplateRequest, GetIamPolicyRegionBackendServiceRequest, GetIamPolicyRegionDiskRequest, + GetIamPolicyRegionInstantSnapshotRequest, GetIamPolicyRegionNetworkFirewallPolicyRequest, GetIamPolicyReservationRequest, GetIamPolicyResourcePolicyRequest, @@ -601,6 +612,7 @@ GetInstanceGroupRequest, GetInstanceRequest, GetInstanceTemplateRequest, + GetInstantSnapshotRequest, GetInterconnectAttachmentRequest, GetInterconnectLocationRequest, GetInterconnectRemoteLocationRequest, @@ -634,6 +646,7 @@ GetRegionInstanceGroupManagerRequest, GetRegionInstanceGroupRequest, GetRegionInstanceTemplateRequest, + GetRegionInstantSnapshotRequest, GetRegionNetworkEndpointGroupRequest, GetRegionNetworkFirewallPolicyRequest, GetRegionNotificationEndpointRequest, @@ -745,6 +758,7 @@ InsertInstanceGroupRequest, InsertInstanceRequest, InsertInstanceTemplateRequest, + InsertInstantSnapshotRequest, InsertInterconnectAttachmentRequest, InsertInterconnectRequest, InsertLicenseRequest, @@ -767,6 +781,7 @@ InsertRegionHealthCheckServiceRequest, InsertRegionInstanceGroupManagerRequest, InsertRegionInstanceTemplateRequest, + InsertRegionInstantSnapshotRequest, InsertRegionNetworkEndpointGroupRequest, InsertRegionNetworkFirewallPolicyRequest, InsertRegionNotificationEndpointRequest, @@ -868,6 +883,11 @@ InstanceTemplateList, InstanceTemplatesScopedList, InstanceWithNamedPorts, + InstantSnapshot, + InstantSnapshotAggregatedList, + InstantSnapshotList, + InstantSnapshotResourceStatus, + InstantSnapshotsScopedList, Int64RangeMatch, Interconnect, InterconnectAttachment, @@ -939,6 +959,7 @@ ListInstancesRegionInstanceGroupsRequest, ListInstancesRequest, ListInstanceTemplatesRequest, + ListInstantSnapshotsRequest, ListInterconnectAttachmentsRequest, ListInterconnectLocationsRequest, ListInterconnectRemoteLocationsRequest, @@ -977,6 +998,7 @@ ListRegionInstanceGroupManagersRequest, ListRegionInstanceGroupsRequest, ListRegionInstanceTemplatesRequest, + ListRegionInstantSnapshotsRequest, ListRegionNetworkEndpointGroupsRequest, ListRegionNetworkFirewallPoliciesRequest, ListRegionNotificationEndpointsRequest, @@ -1187,6 +1209,7 @@ ProjectsEnableXpnResourceRequest, ProjectsGetXpnResources, ProjectsListXpnHostsRequest, + ProjectsSetCloudArmorTierRequest, ProjectsSetDefaultNetworkTierRequest, PublicAdvertisedPrefix, PublicAdvertisedPrefixList, @@ -1368,6 +1391,7 @@ SetBackupTargetPoolRequest, SetCertificateMapTargetHttpsProxyRequest, SetCertificateMapTargetSslProxyRequest, + SetCloudArmorTierProjectRequest, SetCommonInstanceMetadataOperationMetadata, SetCommonInstanceMetadataOperationMetadataPerLocationOperationInfo, SetCommonInstanceMetadataProjectRequest, @@ -1383,6 +1407,7 @@ SetIamPolicyImageRequest, SetIamPolicyInstanceRequest, SetIamPolicyInstanceTemplateRequest, + SetIamPolicyInstantSnapshotRequest, SetIamPolicyLicenseRequest, SetIamPolicyMachineImageRequest, SetIamPolicyNetworkAttachmentRequest, @@ -1391,6 +1416,7 @@ SetIamPolicyNodeTemplateRequest, SetIamPolicyRegionBackendServiceRequest, SetIamPolicyRegionDiskRequest, + SetIamPolicyRegionInstantSnapshotRequest, SetIamPolicyRegionNetworkFirewallPolicyRequest, SetIamPolicyReservationRequest, SetIamPolicyResourcePolicyRequest, @@ -1407,9 +1433,11 @@ SetLabelsGlobalForwardingRuleRequest, SetLabelsImageRequest, SetLabelsInstanceRequest, + SetLabelsInstantSnapshotRequest, SetLabelsInterconnectAttachmentRequest, SetLabelsInterconnectRequest, SetLabelsRegionDiskRequest, + SetLabelsRegionInstantSnapshotRequest, SetLabelsSecurityPolicyRequest, SetLabelsSnapshotRequest, SetLabelsTargetVpnGatewayRequest, @@ -1559,6 +1587,7 @@ TestIamPermissionsImageRequest, TestIamPermissionsInstanceRequest, TestIamPermissionsInstanceTemplateRequest, + TestIamPermissionsInstantSnapshotRequest, TestIamPermissionsLicenseCodeRequest, TestIamPermissionsLicenseRequest, TestIamPermissionsMachineImageRequest, @@ -1570,6 +1599,7 @@ TestIamPermissionsPacketMirroringRequest, TestIamPermissionsRegionBackendServiceRequest, TestIamPermissionsRegionDiskRequest, + TestIamPermissionsRegionInstantSnapshotRequest, TestIamPermissionsRegionNetworkFirewallPolicyRequest, TestIamPermissionsReservationRequest, TestIamPermissionsResourcePolicyRequest, @@ -1682,6 +1712,7 @@ "InstanceGroupsClient", "InstancesClient", "InstanceTemplatesClient", + "InstantSnapshotsClient", "InterconnectAttachmentsClient", "InterconnectLocationsClient", "InterconnectRemoteLocationsClient", @@ -1713,6 +1744,7 @@ "RegionInstanceGroupsClient", "RegionInstancesClient", "RegionInstanceTemplatesClient", + "RegionInstantSnapshotsClient", "RegionNetworkEndpointGroupsClient", "RegionNetworkFirewallPoliciesClient", "RegionNotificationEndpointsClient", @@ -1796,6 +1828,7 @@ "AggregatedListInstanceGroupsRequest", "AggregatedListInstancesRequest", "AggregatedListInstanceTemplatesRequest", + "AggregatedListInstantSnapshotsRequest", "AggregatedListInterconnectAttachmentsRequest", "AggregatedListMachineTypesRequest", "AggregatedListNetworkAttachmentsRequest", @@ -1945,6 +1978,7 @@ "DeleteInstancesInstanceGroupManagerRequest", "DeleteInstancesRegionInstanceGroupManagerRequest", "DeleteInstanceTemplateRequest", + "DeleteInstantSnapshotRequest", "DeleteInterconnectAttachmentRequest", "DeleteInterconnectRequest", "DeleteLicenseRequest", @@ -1969,6 +2003,7 @@ "DeleteRegionHealthCheckServiceRequest", "DeleteRegionInstanceGroupManagerRequest", "DeleteRegionInstanceTemplateRequest", + "DeleteRegionInstantSnapshotRequest", "DeleteRegionNetworkEndpointGroupRequest", "DeleteRegionNetworkFirewallPolicyRequest", "DeleteRegionNotificationEndpointRequest", @@ -2108,6 +2143,7 @@ "GetIamPolicyImageRequest", "GetIamPolicyInstanceRequest", "GetIamPolicyInstanceTemplateRequest", + "GetIamPolicyInstantSnapshotRequest", "GetIamPolicyLicenseRequest", "GetIamPolicyMachineImageRequest", "GetIamPolicyNetworkAttachmentRequest", @@ -2116,6 +2152,7 @@ "GetIamPolicyNodeTemplateRequest", "GetIamPolicyRegionBackendServiceRequest", "GetIamPolicyRegionDiskRequest", + "GetIamPolicyRegionInstantSnapshotRequest", "GetIamPolicyRegionNetworkFirewallPolicyRequest", "GetIamPolicyReservationRequest", "GetIamPolicyResourcePolicyRequest", @@ -2128,6 +2165,7 @@ "GetInstanceGroupRequest", "GetInstanceRequest", "GetInstanceTemplateRequest", + "GetInstantSnapshotRequest", "GetInterconnectAttachmentRequest", "GetInterconnectLocationRequest", "GetInterconnectRemoteLocationRequest", @@ -2161,6 +2199,7 @@ "GetRegionInstanceGroupManagerRequest", "GetRegionInstanceGroupRequest", "GetRegionInstanceTemplateRequest", + "GetRegionInstantSnapshotRequest", "GetRegionNetworkEndpointGroupRequest", "GetRegionNetworkFirewallPolicyRequest", "GetRegionNotificationEndpointRequest", @@ -2272,6 +2311,7 @@ "InsertInstanceGroupRequest", "InsertInstanceRequest", "InsertInstanceTemplateRequest", + "InsertInstantSnapshotRequest", "InsertInterconnectAttachmentRequest", "InsertInterconnectRequest", "InsertLicenseRequest", @@ -2294,6 +2334,7 @@ "InsertRegionHealthCheckServiceRequest", "InsertRegionInstanceGroupManagerRequest", "InsertRegionInstanceTemplateRequest", + "InsertRegionInstantSnapshotRequest", "InsertRegionNetworkEndpointGroupRequest", "InsertRegionNetworkFirewallPolicyRequest", "InsertRegionNotificationEndpointRequest", @@ -2395,6 +2436,11 @@ "InstanceTemplateList", "InstanceTemplatesScopedList", "InstanceWithNamedPorts", + "InstantSnapshot", + "InstantSnapshotAggregatedList", + "InstantSnapshotList", + "InstantSnapshotResourceStatus", + "InstantSnapshotsScopedList", "Int64RangeMatch", "Interconnect", "InterconnectAttachment", @@ -2466,6 +2512,7 @@ "ListInstancesRegionInstanceGroupsRequest", "ListInstancesRequest", "ListInstanceTemplatesRequest", + "ListInstantSnapshotsRequest", "ListInterconnectAttachmentsRequest", "ListInterconnectLocationsRequest", "ListInterconnectRemoteLocationsRequest", @@ -2504,6 +2551,7 @@ "ListRegionInstanceGroupManagersRequest", "ListRegionInstanceGroupsRequest", "ListRegionInstanceTemplatesRequest", + "ListRegionInstantSnapshotsRequest", "ListRegionNetworkEndpointGroupsRequest", "ListRegionNetworkFirewallPoliciesRequest", "ListRegionNotificationEndpointsRequest", @@ -2714,6 +2762,7 @@ "ProjectsEnableXpnResourceRequest", "ProjectsGetXpnResources", "ProjectsListXpnHostsRequest", + "ProjectsSetCloudArmorTierRequest", "ProjectsSetDefaultNetworkTierRequest", "PublicAdvertisedPrefix", "PublicAdvertisedPrefixList", @@ -2895,6 +2944,7 @@ "SetBackupTargetPoolRequest", "SetCertificateMapTargetHttpsProxyRequest", "SetCertificateMapTargetSslProxyRequest", + "SetCloudArmorTierProjectRequest", "SetCommonInstanceMetadataOperationMetadata", "SetCommonInstanceMetadataOperationMetadataPerLocationOperationInfo", "SetCommonInstanceMetadataProjectRequest", @@ -2910,6 +2960,7 @@ "SetIamPolicyImageRequest", "SetIamPolicyInstanceRequest", "SetIamPolicyInstanceTemplateRequest", + "SetIamPolicyInstantSnapshotRequest", "SetIamPolicyLicenseRequest", "SetIamPolicyMachineImageRequest", "SetIamPolicyNetworkAttachmentRequest", @@ -2918,6 +2969,7 @@ "SetIamPolicyNodeTemplateRequest", "SetIamPolicyRegionBackendServiceRequest", "SetIamPolicyRegionDiskRequest", + "SetIamPolicyRegionInstantSnapshotRequest", "SetIamPolicyRegionNetworkFirewallPolicyRequest", "SetIamPolicyReservationRequest", "SetIamPolicyResourcePolicyRequest", @@ -2934,9 +2986,11 @@ "SetLabelsGlobalForwardingRuleRequest", "SetLabelsImageRequest", "SetLabelsInstanceRequest", + "SetLabelsInstantSnapshotRequest", "SetLabelsInterconnectAttachmentRequest", "SetLabelsInterconnectRequest", "SetLabelsRegionDiskRequest", + "SetLabelsRegionInstantSnapshotRequest", "SetLabelsSecurityPolicyRequest", "SetLabelsSnapshotRequest", "SetLabelsTargetVpnGatewayRequest", @@ -3086,6 +3140,7 @@ "TestIamPermissionsImageRequest", "TestIamPermissionsInstanceRequest", "TestIamPermissionsInstanceTemplateRequest", + "TestIamPermissionsInstantSnapshotRequest", "TestIamPermissionsLicenseCodeRequest", "TestIamPermissionsLicenseRequest", "TestIamPermissionsMachineImageRequest", @@ -3097,6 +3152,7 @@ "TestIamPermissionsPacketMirroringRequest", "TestIamPermissionsRegionBackendServiceRequest", "TestIamPermissionsRegionDiskRequest", + "TestIamPermissionsRegionInstantSnapshotRequest", "TestIamPermissionsRegionNetworkFirewallPolicyRequest", "TestIamPermissionsReservationRequest", "TestIamPermissionsResourcePolicyRequest", 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 3293978284a9..1d1b45f2c68a 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.17.0" # {x-release-please-version} +__version__ = "1.18.0" # {x-release-please-version} diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py index 673511504a88..54195181c84b 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py @@ -44,6 +44,7 @@ from .services.instance_groups import InstanceGroupsClient from .services.instance_templates import InstanceTemplatesClient from .services.instances import InstancesClient +from .services.instant_snapshots import InstantSnapshotsClient from .services.interconnect_attachments import InterconnectAttachmentsClient from .services.interconnect_locations import InterconnectLocationsClient from .services.interconnect_remote_locations import InterconnectRemoteLocationsClient @@ -75,6 +76,7 @@ from .services.region_instance_groups import RegionInstanceGroupsClient from .services.region_instance_templates import RegionInstanceTemplatesClient from .services.region_instances import RegionInstancesClient +from .services.region_instant_snapshots import RegionInstantSnapshotsClient from .services.region_network_endpoint_groups import RegionNetworkEndpointGroupsClient from .services.region_network_firewall_policies import ( RegionNetworkFirewallPoliciesClient, @@ -161,6 +163,7 @@ AggregatedListInstanceGroupsRequest, AggregatedListInstancesRequest, AggregatedListInstanceTemplatesRequest, + AggregatedListInstantSnapshotsRequest, AggregatedListInterconnectAttachmentsRequest, AggregatedListMachineTypesRequest, AggregatedListNetworkAttachmentsRequest, @@ -310,6 +313,7 @@ DeleteInstancesInstanceGroupManagerRequest, DeleteInstancesRegionInstanceGroupManagerRequest, DeleteInstanceTemplateRequest, + DeleteInstantSnapshotRequest, DeleteInterconnectAttachmentRequest, DeleteInterconnectRequest, DeleteLicenseRequest, @@ -334,6 +338,7 @@ DeleteRegionHealthCheckServiceRequest, DeleteRegionInstanceGroupManagerRequest, DeleteRegionInstanceTemplateRequest, + DeleteRegionInstantSnapshotRequest, DeleteRegionNetworkEndpointGroupRequest, DeleteRegionNetworkFirewallPolicyRequest, DeleteRegionNotificationEndpointRequest, @@ -473,6 +478,7 @@ GetIamPolicyImageRequest, GetIamPolicyInstanceRequest, GetIamPolicyInstanceTemplateRequest, + GetIamPolicyInstantSnapshotRequest, GetIamPolicyLicenseRequest, GetIamPolicyMachineImageRequest, GetIamPolicyNetworkAttachmentRequest, @@ -481,6 +487,7 @@ GetIamPolicyNodeTemplateRequest, GetIamPolicyRegionBackendServiceRequest, GetIamPolicyRegionDiskRequest, + GetIamPolicyRegionInstantSnapshotRequest, GetIamPolicyRegionNetworkFirewallPolicyRequest, GetIamPolicyReservationRequest, GetIamPolicyResourcePolicyRequest, @@ -493,6 +500,7 @@ GetInstanceGroupRequest, GetInstanceRequest, GetInstanceTemplateRequest, + GetInstantSnapshotRequest, GetInterconnectAttachmentRequest, GetInterconnectLocationRequest, GetInterconnectRemoteLocationRequest, @@ -526,6 +534,7 @@ GetRegionInstanceGroupManagerRequest, GetRegionInstanceGroupRequest, GetRegionInstanceTemplateRequest, + GetRegionInstantSnapshotRequest, GetRegionNetworkEndpointGroupRequest, GetRegionNetworkFirewallPolicyRequest, GetRegionNotificationEndpointRequest, @@ -637,6 +646,7 @@ InsertInstanceGroupRequest, InsertInstanceRequest, InsertInstanceTemplateRequest, + InsertInstantSnapshotRequest, InsertInterconnectAttachmentRequest, InsertInterconnectRequest, InsertLicenseRequest, @@ -659,6 +669,7 @@ InsertRegionHealthCheckServiceRequest, InsertRegionInstanceGroupManagerRequest, InsertRegionInstanceTemplateRequest, + InsertRegionInstantSnapshotRequest, InsertRegionNetworkEndpointGroupRequest, InsertRegionNetworkFirewallPolicyRequest, InsertRegionNotificationEndpointRequest, @@ -760,6 +771,11 @@ InstanceTemplateList, InstanceTemplatesScopedList, InstanceWithNamedPorts, + InstantSnapshot, + InstantSnapshotAggregatedList, + InstantSnapshotList, + InstantSnapshotResourceStatus, + InstantSnapshotsScopedList, Int64RangeMatch, Interconnect, InterconnectAttachment, @@ -831,6 +847,7 @@ ListInstancesRegionInstanceGroupsRequest, ListInstancesRequest, ListInstanceTemplatesRequest, + ListInstantSnapshotsRequest, ListInterconnectAttachmentsRequest, ListInterconnectLocationsRequest, ListInterconnectRemoteLocationsRequest, @@ -869,6 +886,7 @@ ListRegionInstanceGroupManagersRequest, ListRegionInstanceGroupsRequest, ListRegionInstanceTemplatesRequest, + ListRegionInstantSnapshotsRequest, ListRegionNetworkEndpointGroupsRequest, ListRegionNetworkFirewallPoliciesRequest, ListRegionNotificationEndpointsRequest, @@ -1079,6 +1097,7 @@ ProjectsEnableXpnResourceRequest, ProjectsGetXpnResources, ProjectsListXpnHostsRequest, + ProjectsSetCloudArmorTierRequest, ProjectsSetDefaultNetworkTierRequest, PublicAdvertisedPrefix, PublicAdvertisedPrefixList, @@ -1260,6 +1279,7 @@ SetBackupTargetPoolRequest, SetCertificateMapTargetHttpsProxyRequest, SetCertificateMapTargetSslProxyRequest, + SetCloudArmorTierProjectRequest, SetCommonInstanceMetadataOperationMetadata, SetCommonInstanceMetadataOperationMetadataPerLocationOperationInfo, SetCommonInstanceMetadataProjectRequest, @@ -1275,6 +1295,7 @@ SetIamPolicyImageRequest, SetIamPolicyInstanceRequest, SetIamPolicyInstanceTemplateRequest, + SetIamPolicyInstantSnapshotRequest, SetIamPolicyLicenseRequest, SetIamPolicyMachineImageRequest, SetIamPolicyNetworkAttachmentRequest, @@ -1283,6 +1304,7 @@ SetIamPolicyNodeTemplateRequest, SetIamPolicyRegionBackendServiceRequest, SetIamPolicyRegionDiskRequest, + SetIamPolicyRegionInstantSnapshotRequest, SetIamPolicyRegionNetworkFirewallPolicyRequest, SetIamPolicyReservationRequest, SetIamPolicyResourcePolicyRequest, @@ -1299,9 +1321,11 @@ SetLabelsGlobalForwardingRuleRequest, SetLabelsImageRequest, SetLabelsInstanceRequest, + SetLabelsInstantSnapshotRequest, SetLabelsInterconnectAttachmentRequest, SetLabelsInterconnectRequest, SetLabelsRegionDiskRequest, + SetLabelsRegionInstantSnapshotRequest, SetLabelsSecurityPolicyRequest, SetLabelsSnapshotRequest, SetLabelsTargetVpnGatewayRequest, @@ -1451,6 +1475,7 @@ TestIamPermissionsImageRequest, TestIamPermissionsInstanceRequest, TestIamPermissionsInstanceTemplateRequest, + TestIamPermissionsInstantSnapshotRequest, TestIamPermissionsLicenseCodeRequest, TestIamPermissionsLicenseRequest, TestIamPermissionsMachineImageRequest, @@ -1462,6 +1487,7 @@ TestIamPermissionsPacketMirroringRequest, TestIamPermissionsRegionBackendServiceRequest, TestIamPermissionsRegionDiskRequest, + TestIamPermissionsRegionInstantSnapshotRequest, TestIamPermissionsRegionNetworkFirewallPolicyRequest, TestIamPermissionsReservationRequest, TestIamPermissionsResourcePolicyRequest, @@ -1599,6 +1625,7 @@ "AggregatedListInstanceGroupsRequest", "AggregatedListInstanceTemplatesRequest", "AggregatedListInstancesRequest", + "AggregatedListInstantSnapshotsRequest", "AggregatedListInterconnectAttachmentsRequest", "AggregatedListMachineTypesRequest", "AggregatedListNetworkAttachmentsRequest", @@ -1750,6 +1777,7 @@ "DeleteInstanceTemplateRequest", "DeleteInstancesInstanceGroupManagerRequest", "DeleteInstancesRegionInstanceGroupManagerRequest", + "DeleteInstantSnapshotRequest", "DeleteInterconnectAttachmentRequest", "DeleteInterconnectRequest", "DeleteLicenseRequest", @@ -1774,6 +1802,7 @@ "DeleteRegionHealthCheckServiceRequest", "DeleteRegionInstanceGroupManagerRequest", "DeleteRegionInstanceTemplateRequest", + "DeleteRegionInstantSnapshotRequest", "DeleteRegionNetworkEndpointGroupRequest", "DeleteRegionNetworkFirewallPolicyRequest", "DeleteRegionNotificationEndpointRequest", @@ -1920,6 +1949,7 @@ "GetIamPolicyImageRequest", "GetIamPolicyInstanceRequest", "GetIamPolicyInstanceTemplateRequest", + "GetIamPolicyInstantSnapshotRequest", "GetIamPolicyLicenseRequest", "GetIamPolicyMachineImageRequest", "GetIamPolicyNetworkAttachmentRequest", @@ -1928,6 +1958,7 @@ "GetIamPolicyNodeTemplateRequest", "GetIamPolicyRegionBackendServiceRequest", "GetIamPolicyRegionDiskRequest", + "GetIamPolicyRegionInstantSnapshotRequest", "GetIamPolicyRegionNetworkFirewallPolicyRequest", "GetIamPolicyReservationRequest", "GetIamPolicyResourcePolicyRequest", @@ -1940,6 +1971,7 @@ "GetInstanceGroupRequest", "GetInstanceRequest", "GetInstanceTemplateRequest", + "GetInstantSnapshotRequest", "GetInterconnectAttachmentRequest", "GetInterconnectLocationRequest", "GetInterconnectRemoteLocationRequest", @@ -1973,6 +2005,7 @@ "GetRegionInstanceGroupManagerRequest", "GetRegionInstanceGroupRequest", "GetRegionInstanceTemplateRequest", + "GetRegionInstantSnapshotRequest", "GetRegionNetworkEndpointGroupRequest", "GetRegionNetworkFirewallPolicyRequest", "GetRegionNotificationEndpointRequest", @@ -2092,6 +2125,7 @@ "InsertInstanceGroupRequest", "InsertInstanceRequest", "InsertInstanceTemplateRequest", + "InsertInstantSnapshotRequest", "InsertInterconnectAttachmentRequest", "InsertInterconnectRequest", "InsertLicenseRequest", @@ -2114,6 +2148,7 @@ "InsertRegionHealthCheckServiceRequest", "InsertRegionInstanceGroupManagerRequest", "InsertRegionInstanceTemplateRequest", + "InsertRegionInstantSnapshotRequest", "InsertRegionNetworkEndpointGroupRequest", "InsertRegionNetworkFirewallPolicyRequest", "InsertRegionNotificationEndpointRequest", @@ -2219,6 +2254,12 @@ "InstancesSetSecurityPolicyRequest", "InstancesSetServiceAccountRequest", "InstancesStartWithEncryptionKeyRequest", + "InstantSnapshot", + "InstantSnapshotAggregatedList", + "InstantSnapshotList", + "InstantSnapshotResourceStatus", + "InstantSnapshotsClient", + "InstantSnapshotsScopedList", "Int64RangeMatch", "Interconnect", "InterconnectAttachment", @@ -2296,6 +2337,7 @@ "ListInstancesInstanceGroupsRequest", "ListInstancesRegionInstanceGroupsRequest", "ListInstancesRequest", + "ListInstantSnapshotsRequest", "ListInterconnectAttachmentsRequest", "ListInterconnectLocationsRequest", "ListInterconnectRemoteLocationsRequest", @@ -2334,6 +2376,7 @@ "ListRegionInstanceGroupManagersRequest", "ListRegionInstanceGroupsRequest", "ListRegionInstanceTemplatesRequest", + "ListRegionInstantSnapshotsRequest", "ListRegionNetworkEndpointGroupsRequest", "ListRegionNetworkFirewallPoliciesRequest", "ListRegionNotificationEndpointsRequest", @@ -2556,6 +2599,7 @@ "ProjectsEnableXpnResourceRequest", "ProjectsGetXpnResources", "ProjectsListXpnHostsRequest", + "ProjectsSetCloudArmorTierRequest", "ProjectsSetDefaultNetworkTierRequest", "PublicAdvertisedPrefix", "PublicAdvertisedPrefixList", @@ -2610,6 +2654,7 @@ "RegionInstanceGroupsSetNamedPortsRequest", "RegionInstanceTemplatesClient", "RegionInstancesClient", + "RegionInstantSnapshotsClient", "RegionList", "RegionNetworkEndpointGroupsAttachEndpointsRequest", "RegionNetworkEndpointGroupsClient", @@ -2770,6 +2815,7 @@ "SetBackupTargetPoolRequest", "SetCertificateMapTargetHttpsProxyRequest", "SetCertificateMapTargetSslProxyRequest", + "SetCloudArmorTierProjectRequest", "SetCommonInstanceMetadataOperationMetadata", "SetCommonInstanceMetadataOperationMetadataPerLocationOperationInfo", "SetCommonInstanceMetadataProjectRequest", @@ -2785,6 +2831,7 @@ "SetIamPolicyImageRequest", "SetIamPolicyInstanceRequest", "SetIamPolicyInstanceTemplateRequest", + "SetIamPolicyInstantSnapshotRequest", "SetIamPolicyLicenseRequest", "SetIamPolicyMachineImageRequest", "SetIamPolicyNetworkAttachmentRequest", @@ -2793,6 +2840,7 @@ "SetIamPolicyNodeTemplateRequest", "SetIamPolicyRegionBackendServiceRequest", "SetIamPolicyRegionDiskRequest", + "SetIamPolicyRegionInstantSnapshotRequest", "SetIamPolicyRegionNetworkFirewallPolicyRequest", "SetIamPolicyReservationRequest", "SetIamPolicyResourcePolicyRequest", @@ -2809,9 +2857,11 @@ "SetLabelsGlobalForwardingRuleRequest", "SetLabelsImageRequest", "SetLabelsInstanceRequest", + "SetLabelsInstantSnapshotRequest", "SetLabelsInterconnectAttachmentRequest", "SetLabelsInterconnectRequest", "SetLabelsRegionDiskRequest", + "SetLabelsRegionInstantSnapshotRequest", "SetLabelsSecurityPolicyRequest", "SetLabelsSnapshotRequest", "SetLabelsTargetVpnGatewayRequest", @@ -2973,6 +3023,7 @@ "TestIamPermissionsImageRequest", "TestIamPermissionsInstanceRequest", "TestIamPermissionsInstanceTemplateRequest", + "TestIamPermissionsInstantSnapshotRequest", "TestIamPermissionsLicenseCodeRequest", "TestIamPermissionsLicenseRequest", "TestIamPermissionsMachineImageRequest", @@ -2984,6 +3035,7 @@ "TestIamPermissionsPacketMirroringRequest", "TestIamPermissionsRegionBackendServiceRequest", "TestIamPermissionsRegionDiskRequest", + "TestIamPermissionsRegionInstantSnapshotRequest", "TestIamPermissionsRegionNetworkFirewallPolicyRequest", "TestIamPermissionsReservationRequest", "TestIamPermissionsResourcePolicyRequest", diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json b/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json index 979286888983..494060e6d6df 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json +++ b/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json @@ -1426,6 +1426,60 @@ } } }, + "InstantSnapshots": { + "clients": { + "rest": { + "libraryClient": "InstantSnapshotsClient", + "rpcs": { + "AggregatedList": { + "methods": [ + "aggregated_list" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetLabels": { + "methods": [ + "set_labels" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, "InterconnectAttachments": { "clients": { "rest": { @@ -2234,6 +2288,11 @@ "move_instance" ] }, + "SetCloudArmorTier": { + "methods": [ + "set_cloud_armor_tier" + ] + }, "SetCommonInstanceMetadata": { "methods": [ "set_common_instance_metadata" @@ -2850,6 +2909,55 @@ } } }, + "RegionInstantSnapshots": { + "clients": { + "rest": { + "libraryClient": "RegionInstantSnapshotsClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetLabels": { + "methods": [ + "set_labels" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + } + } + } + } + }, "RegionNetworkEndpointGroups": { "clients": { "rest": { 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 3293978284a9..1d1b45f2c68a 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.17.0" # {x-release-please-version} +__version__ = "1.18.0" # {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 3735b663571b..0ac3a9c5d5db 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 @@ -656,7 +656,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of accelerator types. + r"""Retrieves an aggregated list of accelerator types. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 b5e7781bf7a8..cb427e8e4c8d 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 @@ -649,7 +649,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of addresses. + r"""Retrieves an aggregated list of addresses. To prevent failure, + Google recommends that you set the ``returnPartialSuccess`` + parameter to ``true``. .. code-block:: python 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 85cbf293a316..309717ee4976 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 @@ -649,7 +649,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of autoscalers. + r"""Retrieves an aggregated list of autoscalers. To prevent failure, + Google recommends that you set the ``returnPartialSuccess`` + parameter to ``true``. .. code-block:: python 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 22a4340224b2..aeb0ff2edb11 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 @@ -946,8 +946,10 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves the list of all BackendService resources, - regional and global, available to the specified project. + r"""Retrieves the list of all BackendService resources, regional and + global, available to the specified project. To prevent failure, + Google recommends that you set the ``returnPartialSuccess`` + parameter to ``true``. .. code-block:: python 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 c61cf219674d..d8e5871284a6 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 @@ -646,7 +646,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of disk types. + r"""Retrieves an aggregated list of disk types. To prevent failure, + Google recommends that you set the ``returnPartialSuccess`` + parameter to ``true``. .. code-block:: python 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 7443414d61b4..85a6419ab474 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 @@ -966,7 +966,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of persistent disks. + r"""Retrieves an aggregated list of persistent disks. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 fb432f48e942..de0a54146b87 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 @@ -656,7 +656,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of forwarding rules. + r"""Retrieves an aggregated list of forwarding rules. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 5085c273e064..9535c4ea0633 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 @@ -653,7 +653,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of all operations. + r"""Retrieves an aggregated list of all operations. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 781e26fe8e45..8b03d11327a9 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 @@ -651,8 +651,10 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves the list of all HealthCheck resources, - regional and global, available to the specified project. + r"""Retrieves the list of all HealthCheck resources, regional and + global, available to the specified project. To prevent failure, + Google recommends that you set the ``returnPartialSuccess`` + parameter to ``true``. .. code-block:: python 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 40920361bd7d..fb00b7f18ebc 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 @@ -1019,8 +1019,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves the list of managed instance groups and - groups them by zone. + r"""Retrieves the list of managed instance groups and groups them by + zone. To prevent failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 28089fbd3665..42276b137836 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 @@ -989,8 +989,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves the list of instance groups and sorts them - by zone. + r"""Retrieves the list of instance groups and sorts them by zone. To + prevent failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 62fd9879214d..da861a207500 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 @@ -656,9 +656,10 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves the list of all InstanceTemplates - resources, regional and global, available to the - specified project. + r"""Retrieves the list of all InstanceTemplates resources, regional + and global, available to the specified project. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 23da6a6daf34..4db20b4bb141 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 @@ -1299,11 +1299,12 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of all of the instances - in your project across all regions and zones. The - performance of this method degrades when a filter is - specified on a project that has a very large number of - instances. + r"""Retrieves an aggregated list of all of the instances in your + project across all regions and zones. The performance of this + method degrades when a filter is specified on a project that has + a very large number of instances. To prevent failure, Google + recommends that you set the ``returnPartialSuccess`` parameter + to ``true``. .. code-block:: python diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/__init__.py new file mode 100644 index 000000000000..160c5f1f5779 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import InstantSnapshotsClient + +__all__ = ("InstantSnapshotsClient",) 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 new file mode 100644 index 000000000000..acd0d7b732b1 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/client.py @@ -0,0 +1,2420 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import os +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import extended_operation, gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import extended_operation # type: ignore + +from google.cloud.compute_v1.services.instant_snapshots import pagers +from google.cloud.compute_v1.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, InstantSnapshotsTransport +from .transports.rest import InstantSnapshotsRestTransport + + +class InstantSnapshotsClientMeta(type): + """Metaclass for the InstantSnapshots client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[InstantSnapshotsTransport]] + _transport_registry["rest"] = InstantSnapshotsRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[InstantSnapshotsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class InstantSnapshotsClient(metaclass=InstantSnapshotsClientMeta): + """The InstantSnapshots API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "compute.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "compute.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + InstantSnapshotsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + InstantSnapshotsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> InstantSnapshotsTransport: + """Returns the transport used by the client instance. + + Returns: + InstantSnapshotsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = InstantSnapshotsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = InstantSnapshotsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = InstantSnapshotsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = InstantSnapshotsClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + 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. + + Returns: + bool: True iff the configured universe domain is valid. + + 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 + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, InstantSnapshotsTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the instant snapshots client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, InstantSnapshotsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = InstantSnapshotsClient._read_environment_variables() + self._client_cert_source = InstantSnapshotsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = InstantSnapshotsClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, InstantSnapshotsTransport) + if transport_provided: + # transport is a InstantSnapshotsTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(InstantSnapshotsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or InstantSnapshotsClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + Transport = type(self).get_transport_class(cast(str, transport)) + self._transport = Transport( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def aggregated_list( + self, + request: Optional[ + Union[compute.AggregatedListInstantSnapshotsRequest, dict] + ] = None, + *, + project: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.AggregatedListPager: + r"""Retrieves an aggregated list of instantSnapshots. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_aggregated_list(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.AggregatedListInstantSnapshotsRequest( + project="project_value", + ) + + # Make the request + page_result = client.aggregated_list(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.AggregatedListInstantSnapshotsRequest, dict]): + The request object. A request message for + InstantSnapshots.AggregatedList. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.services.instant_snapshots.pagers.AggregatedListPager: + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.AggregatedListInstantSnapshotsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.AggregatedListInstantSnapshotsRequest): + request = compute.AggregatedListInstantSnapshotsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.aggregated_list] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.AggregatedListPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_unary( + self, + request: Optional[Union[compute.DeleteInstantSnapshotRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + instant_snapshot: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Deletes the specified InstantSnapshot resource. Keep + in mind that deleting a single instantSnapshot might not + necessarily delete all the data on that instantSnapshot. + If any data on the instantSnapshot that is marked for + deletion is needed for subsequent instantSnapshots, the + data will be moved to the next corresponding + instantSnapshot. For more information, see Deleting + instantSnapshots. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_delete(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.DeleteInstantSnapshotRequest( + instant_snapshot="instant_snapshot_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.DeleteInstantSnapshotRequest, dict]): + The request object. A request message for + InstantSnapshots.Delete. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + The name of the zone for this + request. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instant_snapshot (str): + Name of the InstantSnapshot resource + to delete. + + This corresponds to the ``instant_snapshot`` 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.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, zone, instant_snapshot]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.DeleteInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.DeleteInstantSnapshotRequest): + request = compute.DeleteInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if instant_snapshot is not None: + request.instant_snapshot = instant_snapshot + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ("instant_snapshot", request.instant_snapshot), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete( + self, + request: Optional[Union[compute.DeleteInstantSnapshotRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + instant_snapshot: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Deletes the specified InstantSnapshot resource. Keep + in mind that deleting a single instantSnapshot might not + necessarily delete all the data on that instantSnapshot. + If any data on the instantSnapshot that is marked for + deletion is needed for subsequent instantSnapshots, the + data will be moved to the next corresponding + instantSnapshot. For more information, see Deleting + instantSnapshots. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_delete(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.DeleteInstantSnapshotRequest( + instant_snapshot="instant_snapshot_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.DeleteInstantSnapshotRequest, dict]): + The request object. A request message for + InstantSnapshots.Delete. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + The name of the zone for this + request. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instant_snapshot (str): + Name of the InstantSnapshot resource + to delete. + + This corresponds to the ``instant_snapshot`` 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.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, zone, instant_snapshot]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.DeleteInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.DeleteInstantSnapshotRequest): + request = compute.DeleteInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if instant_snapshot is not None: + request.instant_snapshot = instant_snapshot + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ("instant_snapshot", request.instant_snapshot), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._zone_operations_client + operation_request = compute.GetZoneOperationRequest() + operation_request.project = request.project + operation_request.zone = request.zone + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def get( + self, + request: Optional[Union[compute.GetInstantSnapshotRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + instant_snapshot: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.InstantSnapshot: + r"""Returns the specified InstantSnapshot resource in the + specified zone. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_get(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.GetInstantSnapshotRequest( + instant_snapshot="instant_snapshot_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.GetInstantSnapshotRequest, dict]): + The request object. A request message for + InstantSnapshots.Get. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + The name of the zone for this + request. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instant_snapshot (str): + Name of the InstantSnapshot resource + to return. + + This corresponds to the ``instant_snapshot`` 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.compute_v1.types.InstantSnapshot: + Represents a InstantSnapshot + resource. You can use instant snapshots + to create disk rollback points quickly.. + + """ + # 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([project, zone, instant_snapshot]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.GetInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.GetInstantSnapshotRequest): + request = compute.GetInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if instant_snapshot is not None: + request.instant_snapshot = instant_snapshot + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ("instant_snapshot", request.instant_snapshot), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[ + Union[compute.GetIamPolicyInstantSnapshotRequest, dict] + ] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Policy: + r"""Gets the access control policy for a resource. May be + empty if no such policy or resource exists. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_get_iam_policy(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.GetIamPolicyInstantSnapshotRequest( + project="project_value", + resource="resource_value", + zone="zone_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.GetIamPolicyInstantSnapshotRequest, dict]): + The request object. A request message for + InstantSnapshots.GetIamPolicy. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + The name of the zone for this + request. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. A + Policy is a collection of bindings. A binding binds one + or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role is + a named list of permissions; each role can be an IAM + predefined role or a user-created custom role. For some + types of Google Cloud resources, a binding can also + specify a condition, which is a logical expression that + allows access to a resource only if the expression + evaluates to true. A condition can add constraints based + on attributes of the request, the resource, or both. To + learn which resources support conditions in their IAM + policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + **JSON example:** + :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + **YAML example:** + :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + For a description of IAM and its features, see the [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, zone, resource]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.GetIamPolicyInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.GetIamPolicyInstantSnapshotRequest): + request = compute.GetIamPolicyInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ("resource", request.resource), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert_unary( + self, + request: Optional[Union[compute.InsertInstantSnapshotRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + instant_snapshot_resource: Optional[compute.InstantSnapshot] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Creates an instant snapshot in the specified zone. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_insert(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.InsertInstantSnapshotRequest( + project="project_value", + zone="zone_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.InsertInstantSnapshotRequest, dict]): + The request object. A request message for + InstantSnapshots.Insert. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + Name of the zone for this request. + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instant_snapshot_resource (google.cloud.compute_v1.types.InstantSnapshot): + The body resource for this request + This corresponds to the ``instant_snapshot_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, zone, instant_snapshot_resource]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.InsertInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.InsertInstantSnapshotRequest): + request = compute.InsertInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if instant_snapshot_resource is not None: + request.instant_snapshot_resource = instant_snapshot_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert( + self, + request: Optional[Union[compute.InsertInstantSnapshotRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + instant_snapshot_resource: Optional[compute.InstantSnapshot] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Creates an instant snapshot in the specified zone. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_insert(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.InsertInstantSnapshotRequest( + project="project_value", + zone="zone_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.InsertInstantSnapshotRequest, dict]): + The request object. A request message for + InstantSnapshots.Insert. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + Name of the zone for this request. + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instant_snapshot_resource (google.cloud.compute_v1.types.InstantSnapshot): + The body resource for this request + This corresponds to the ``instant_snapshot_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, zone, instant_snapshot_resource]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.InsertInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.InsertInstantSnapshotRequest): + request = compute.InsertInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if instant_snapshot_resource is not None: + request.instant_snapshot_resource = instant_snapshot_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._zone_operations_client + operation_request = compute.GetZoneOperationRequest() + operation_request.project = request.project + operation_request.zone = request.zone + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def list( + self, + request: Optional[Union[compute.ListInstantSnapshotsRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPager: + r"""Retrieves the list of InstantSnapshot resources + contained within the specified zone. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_list(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.ListInstantSnapshotsRequest( + project="project_value", + zone="zone_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.ListInstantSnapshotsRequest, dict]): + The request object. A request message for + InstantSnapshots.List. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + The name of the zone for this + request. + + This corresponds to the ``zone`` 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.compute_v1.services.instant_snapshots.pagers.ListPager: + Contains a list of InstantSnapshot + resources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, zone]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.ListInstantSnapshotsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.ListInstantSnapshotsRequest): + request = compute.ListInstantSnapshotsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: Optional[ + Union[compute.SetIamPolicyInstantSnapshotRequest, dict] + ] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + resource: Optional[str] = None, + zone_set_policy_request_resource: Optional[compute.ZoneSetPolicyRequest] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Policy: + r"""Sets the access control policy on the specified + resource. Replaces any existing policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_set_iam_policy(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.SetIamPolicyInstantSnapshotRequest( + project="project_value", + resource="resource_value", + zone="zone_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.SetIamPolicyInstantSnapshotRequest, dict]): + The request object. A request message for + InstantSnapshots.SetIamPolicy. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + The name of the zone for this + request. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone_set_policy_request_resource (google.cloud.compute_v1.types.ZoneSetPolicyRequest): + The body resource for this request + This corresponds to the ``zone_set_policy_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. A + Policy is a collection of bindings. A binding binds one + or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role is + a named list of permissions; each role can be an IAM + predefined role or a user-created custom role. For some + types of Google Cloud resources, a binding can also + specify a condition, which is a logical expression that + allows access to a resource only if the expression + evaluates to true. A condition can add constraints based + on attributes of the request, the resource, or both. To + learn which resources support conditions in their IAM + policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + **JSON example:** + :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + **YAML example:** + :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + For a description of IAM and its features, see the [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any( + [project, zone, resource, zone_set_policy_request_resource] + ) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.SetIamPolicyInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.SetIamPolicyInstantSnapshotRequest): + request = compute.SetIamPolicyInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if resource is not None: + request.resource = resource + if zone_set_policy_request_resource is not None: + request.zone_set_policy_request_resource = ( + zone_set_policy_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ("resource", request.resource), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_labels_unary( + self, + request: Optional[Union[compute.SetLabelsInstantSnapshotRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + resource: Optional[str] = None, + zone_set_labels_request_resource: Optional[compute.ZoneSetLabelsRequest] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Sets the labels on a instantSnapshot in the given + zone. To learn more about labels, read the Labeling + Resources documentation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_set_labels(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.SetLabelsInstantSnapshotRequest( + project="project_value", + resource="resource_value", + zone="zone_value", + ) + + # Make the request + response = client.set_labels(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.SetLabelsInstantSnapshotRequest, dict]): + The request object. A request message for + InstantSnapshots.SetLabels. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + The name of the zone for this + request. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone_set_labels_request_resource (google.cloud.compute_v1.types.ZoneSetLabelsRequest): + The body resource for this request + This corresponds to the ``zone_set_labels_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any( + [project, zone, resource, zone_set_labels_request_resource] + ) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.SetLabelsInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.SetLabelsInstantSnapshotRequest): + request = compute.SetLabelsInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if resource is not None: + request.resource = resource + if zone_set_labels_request_resource is not None: + request.zone_set_labels_request_resource = ( + zone_set_labels_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_labels] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ("resource", request.resource), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_labels( + self, + request: Optional[Union[compute.SetLabelsInstantSnapshotRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + resource: Optional[str] = None, + zone_set_labels_request_resource: Optional[compute.ZoneSetLabelsRequest] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Sets the labels on a instantSnapshot in the given + zone. To learn more about labels, read the Labeling + Resources documentation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_set_labels(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.SetLabelsInstantSnapshotRequest( + project="project_value", + resource="resource_value", + zone="zone_value", + ) + + # Make the request + response = client.set_labels(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.SetLabelsInstantSnapshotRequest, dict]): + The request object. A request message for + InstantSnapshots.SetLabels. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + The name of the zone for this + request. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone_set_labels_request_resource (google.cloud.compute_v1.types.ZoneSetLabelsRequest): + The body resource for this request + This corresponds to the ``zone_set_labels_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any( + [project, zone, resource, zone_set_labels_request_resource] + ) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.SetLabelsInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.SetLabelsInstantSnapshotRequest): + request = compute.SetLabelsInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if resource is not None: + request.resource = resource + if zone_set_labels_request_resource is not None: + request.zone_set_labels_request_resource = ( + zone_set_labels_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_labels] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ("resource", request.resource), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._zone_operations_client + operation_request = compute.GetZoneOperationRequest() + operation_request.project = request.project + operation_request.zone = request.zone + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[ + Union[compute.TestIamPermissionsInstantSnapshotRequest, dict] + ] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + resource: Optional[str] = None, + test_permissions_request_resource: Optional[ + compute.TestPermissionsRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.TestPermissionsResponse: + r"""Returns permissions that a caller has on the + specified resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_test_iam_permissions(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.TestIamPermissionsInstantSnapshotRequest( + project="project_value", + resource="resource_value", + zone="zone_value", + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.TestIamPermissionsInstantSnapshotRequest, dict]): + The request object. A request message for + InstantSnapshots.TestIamPermissions. See + the method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + The name of the zone for this + request. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + test_permissions_request_resource (google.cloud.compute_v1.types.TestPermissionsRequest): + The body resource for this request + This corresponds to the ``test_permissions_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.TestPermissionsResponse: + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any( + [project, zone, resource, test_permissions_request_resource] + ) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.TestIamPermissionsInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.TestIamPermissionsInstantSnapshotRequest): + request = compute.TestIamPermissionsInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if resource is not None: + request.resource = resource + if test_permissions_request_resource is not None: + request.test_permissions_request_resource = ( + test_permissions_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ("resource", request.resource), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "InstantSnapshotsClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("InstantSnapshotsClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/pagers.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/pagers.py new file mode 100644 index 000000000000..025459ae0acc --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/pagers.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.compute_v1.types import compute + + +class AggregatedListPager: + """A pager for iterating through ``aggregated_list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.compute_v1.types.InstantSnapshotAggregatedList` object, and + provides an ``__iter__`` method to iterate through its + ``items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``AggregatedList`` requests and continue to iterate + through the ``items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.compute_v1.types.InstantSnapshotAggregatedList` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., compute.InstantSnapshotAggregatedList], + request: compute.AggregatedListInstantSnapshotsRequest, + response: compute.InstantSnapshotAggregatedList, + *, + 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.compute_v1.types.AggregatedListInstantSnapshotsRequest): + The initial request object. + response (google.cloud.compute_v1.types.InstantSnapshotAggregatedList): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = compute.AggregatedListInstantSnapshotsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[compute.InstantSnapshotAggregatedList]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[Tuple[str, compute.InstantSnapshotsScopedList]]: + for page in self.pages: + yield from page.items.items() + + def get(self, key: str) -> Optional[compute.InstantSnapshotsScopedList]: + return self._response.items.get(key) + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListPager: + """A pager for iterating through ``list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.compute_v1.types.InstantSnapshotList` object, and + provides an ``__iter__`` method to iterate through its + ``items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``List`` requests and continue to iterate + through the ``items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.compute_v1.types.InstantSnapshotList` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., compute.InstantSnapshotList], + request: compute.ListInstantSnapshotsRequest, + response: compute.InstantSnapshotList, + *, + 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.compute_v1.types.ListInstantSnapshotsRequest): + The initial request object. + response (google.cloud.compute_v1.types.InstantSnapshotList): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = compute.ListInstantSnapshotsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[compute.InstantSnapshotList]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[compute.InstantSnapshot]: + for page in self.pages: + yield from page.items + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/transports/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/transports/__init__.py new file mode 100644 index 000000000000..9e7b836b2fd7 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import InstantSnapshotsTransport +from .rest import InstantSnapshotsRestInterceptor, InstantSnapshotsRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[InstantSnapshotsTransport]] +_transport_registry["rest"] = InstantSnapshotsRestTransport + +__all__ = ( + "InstantSnapshotsTransport", + "InstantSnapshotsRestTransport", + "InstantSnapshotsRestInterceptor", +) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/transports/base.py new file mode 100644 index 000000000000..db901869fbab --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/transports/base.py @@ -0,0 +1,293 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1 import gapic_version as package_version +from google.cloud.compute_v1.services import zone_operations +from google.cloud.compute_v1.types import compute + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class InstantSnapshotsTransport(abc.ABC): + """Abstract transport class for InstantSnapshots.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "compute.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + self._extended_operations_services: Dict[str, Any] = {} + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.aggregated_list: gapic_v1.method.wrap_method( + self.aggregated_list, + default_timeout=None, + client_info=client_info, + ), + self.delete: gapic_v1.method.wrap_method( + self.delete, + default_timeout=None, + client_info=client_info, + ), + self.get: gapic_v1.method.wrap_method( + self.get, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.insert: gapic_v1.method.wrap_method( + self.insert, + default_timeout=None, + client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_labels: gapic_v1.method.wrap_method( + self.set_labels, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def aggregated_list( + self, + ) -> Callable[ + [compute.AggregatedListInstantSnapshotsRequest], + Union[ + compute.InstantSnapshotAggregatedList, + Awaitable[compute.InstantSnapshotAggregatedList], + ], + ]: + raise NotImplementedError() + + @property + def delete( + self, + ) -> Callable[ + [compute.DeleteInstantSnapshotRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetInstantSnapshotRequest], + Union[compute.InstantSnapshot, Awaitable[compute.InstantSnapshot]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [compute.GetIamPolicyInstantSnapshotRequest], + Union[compute.Policy, Awaitable[compute.Policy]], + ]: + raise NotImplementedError() + + @property + def insert( + self, + ) -> Callable[ + [compute.InsertInstantSnapshotRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListInstantSnapshotsRequest], + Union[compute.InstantSnapshotList, Awaitable[compute.InstantSnapshotList]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [compute.SetIamPolicyInstantSnapshotRequest], + Union[compute.Policy, Awaitable[compute.Policy]], + ]: + raise NotImplementedError() + + @property + def set_labels( + self, + ) -> Callable[ + [compute.SetLabelsInstantSnapshotRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [compute.TestIamPermissionsInstantSnapshotRequest], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + @property + def _zone_operations_client(self) -> zone_operations.ZoneOperationsClient: + ex_op_service = self._extended_operations_services.get("zone_operations") + if not ex_op_service: + ex_op_service = zone_operations.ZoneOperationsClient( + credentials=self._credentials, + transport=self.kind, + ) + self._extended_operations_services["zone_operations"] = ex_op_service + + return ex_op_service + + +__all__ = ("InstantSnapshotsTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/transports/rest.py new file mode 100644 index 000000000000..c7a8242608ba --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instant_snapshots/transports/rest.py @@ -0,0 +1,1430 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.compute_v1.types import compute + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import InstantSnapshotsTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class InstantSnapshotsRestInterceptor: + """Interceptor for InstantSnapshots. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the InstantSnapshotsRestTransport. + + .. code-block:: python + class MyCustomInstantSnapshotsInterceptor(InstantSnapshotsRestInterceptor): + def pre_aggregated_list(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_aggregated_list(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_insert(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_labels(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_labels(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + transport = InstantSnapshotsRestTransport(interceptor=MyCustomInstantSnapshotsInterceptor()) + client = InstantSnapshotsClient(transport=transport) + + + """ + + def pre_aggregated_list( + self, + request: compute.AggregatedListInstantSnapshotsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + compute.AggregatedListInstantSnapshotsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for aggregated_list + + Override in a subclass to manipulate the request or metadata + before they are sent to the InstantSnapshots server. + """ + return request, metadata + + def post_aggregated_list( + self, response: compute.InstantSnapshotAggregatedList + ) -> compute.InstantSnapshotAggregatedList: + """Post-rpc interceptor for aggregated_list + + Override in a subclass to manipulate the response + after it is returned by the InstantSnapshots server but before + it is returned to user code. + """ + return response + + def pre_delete( + self, + request: compute.DeleteInstantSnapshotRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.DeleteInstantSnapshotRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete + + Override in a subclass to manipulate the request or metadata + before they are sent to the InstantSnapshots server. + """ + return request, metadata + + def post_delete(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for delete + + Override in a subclass to manipulate the response + after it is returned by the InstantSnapshots server but before + it is returned to user code. + """ + return response + + def pre_get( + self, + request: compute.GetInstantSnapshotRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.GetInstantSnapshotRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get + + Override in a subclass to manipulate the request or metadata + before they are sent to the InstantSnapshots server. + """ + return request, metadata + + def post_get(self, response: compute.InstantSnapshot) -> compute.InstantSnapshot: + """Post-rpc interceptor for get + + Override in a subclass to manipulate the response + after it is returned by the InstantSnapshots server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: compute.GetIamPolicyInstantSnapshotRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.GetIamPolicyInstantSnapshotRequest, 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 InstantSnapshots server. + """ + return request, metadata + + def post_get_iam_policy(self, response: compute.Policy) -> compute.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the InstantSnapshots server but before + it is returned to user code. + """ + return response + + def pre_insert( + self, + request: compute.InsertInstantSnapshotRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.InsertInstantSnapshotRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for insert + + Override in a subclass to manipulate the request or metadata + before they are sent to the InstantSnapshots server. + """ + return request, metadata + + def post_insert(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for insert + + Override in a subclass to manipulate the response + after it is returned by the InstantSnapshots server but before + it is returned to user code. + """ + return response + + def pre_list( + self, + request: compute.ListInstantSnapshotsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.ListInstantSnapshotsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list + + Override in a subclass to manipulate the request or metadata + before they are sent to the InstantSnapshots server. + """ + return request, metadata + + def post_list( + self, response: compute.InstantSnapshotList + ) -> compute.InstantSnapshotList: + """Post-rpc interceptor for list + + Override in a subclass to manipulate the response + after it is returned by the InstantSnapshots server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: compute.SetIamPolicyInstantSnapshotRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.SetIamPolicyInstantSnapshotRequest, 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 InstantSnapshots server. + """ + return request, metadata + + def post_set_iam_policy(self, response: compute.Policy) -> compute.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the InstantSnapshots server but before + it is returned to user code. + """ + return response + + def pre_set_labels( + self, + request: compute.SetLabelsInstantSnapshotRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.SetLabelsInstantSnapshotRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_labels + + Override in a subclass to manipulate the request or metadata + before they are sent to the InstantSnapshots server. + """ + return request, metadata + + def post_set_labels(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for set_labels + + Override in a subclass to manipulate the response + after it is returned by the InstantSnapshots server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: compute.TestIamPermissionsInstantSnapshotRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + compute.TestIamPermissionsInstantSnapshotRequest, 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 InstantSnapshots server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: compute.TestPermissionsResponse + ) -> compute.TestPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the InstantSnapshots server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class InstantSnapshotsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: InstantSnapshotsRestInterceptor + + +class InstantSnapshotsRestTransport(InstantSnapshotsTransport): + """REST backend transport for InstantSnapshots. + + The InstantSnapshots API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via an issue in this + library's source repository. Thank you! + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[InstantSnapshotsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): 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 + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or InstantSnapshotsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AggregatedList(InstantSnapshotsRestStub): + def __hash__(self): + return hash("AggregatedList") + + __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 + } + + def __call__( + self, + request: compute.AggregatedListInstantSnapshotsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.InstantSnapshotAggregatedList: + r"""Call the aggregated list method over HTTP. + + Args: + request (~.compute.AggregatedListInstantSnapshotsRequest): + The request object. A request message for + InstantSnapshots.AggregatedList. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.InstantSnapshotAggregatedList: + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/aggregated/instantSnapshots", + }, + ] + request, metadata = self._interceptor.pre_aggregated_list(request, metadata) + pb_request = compute.AggregatedListInstantSnapshotsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.InstantSnapshotAggregatedList() + pb_resp = compute.InstantSnapshotAggregatedList.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_aggregated_list(resp) + return resp + + class _Delete(InstantSnapshotsRestStub): + def __hash__(self): + return hash("Delete") + + __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 + } + + def __call__( + self, + request: compute.DeleteInstantSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the delete method over HTTP. + + Args: + request (~.compute.DeleteInstantSnapshotRequest): + The request object. A request message for + InstantSnapshots.Delete. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.Operation: + Represents an Operation resource. Google Compute Engine + has three Operation resources: \* + `Global `__ + \* + `Regional `__ + \* + `Zonal `__ + You can use an operation resource to manage asynchronous + API requests. For more information, read Handling API + responses. Operations can be global, regional or zonal. + - For global operations, use the ``globalOperations`` + resource. - For regional operations, use the + ``regionOperations`` resource. - For zonal operations, + use the ``zoneOperations`` resource. For more + information, read Global, Regional, and Zonal Resources. + Note that completed Operation resources have a limited + retention period. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/compute/v1/projects/{project}/zones/{zone}/instantSnapshots/{instant_snapshot}", + }, + ] + request, metadata = self._interceptor.pre_delete(request, metadata) + pb_request = compute.DeleteInstantSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete(resp) + return resp + + class _Get(InstantSnapshotsRestStub): + def __hash__(self): + return hash("Get") + + __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 + } + + def __call__( + self, + request: compute.GetInstantSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.InstantSnapshot: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetInstantSnapshotRequest): + The request object. A request message for + InstantSnapshots.Get. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.InstantSnapshot: + Represents a InstantSnapshot + resource. You can use instant snapshots + to create disk rollback points quickly.. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/zones/{zone}/instantSnapshots/{instant_snapshot}", + }, + ] + request, metadata = self._interceptor.pre_get(request, metadata) + pb_request = compute.GetInstantSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.InstantSnapshot() + pb_resp = compute.InstantSnapshot.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get(resp) + return resp + + class _GetIamPolicy(InstantSnapshotsRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __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 + } + + def __call__( + self, + request: compute.GetIamPolicyInstantSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (~.compute.GetIamPolicyInstantSnapshotRequest): + The request object. A request message for + InstantSnapshots.GetIamPolicy. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. A + ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. For some types of Google + Cloud resources, a ``binding`` can also specify a + ``condition``, which is a logical expression that allows + access to a resource only if the expression evaluates to + ``true``. A condition can add constraints based on + attributes of the request, the resource, or both. To + learn which resources support conditions in their IAM + policies, see the `IAM + documentation `__. + **JSON example:** + ``{ "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`` + **YAML example:** + ``bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`` + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/zones/{zone}/instantSnapshots/{resource}/getIamPolicy", + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = compute.GetIamPolicyInstantSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Policy() + pb_resp = compute.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _Insert(InstantSnapshotsRestStub): + def __hash__(self): + return hash("Insert") + + __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 + } + + def __call__( + self, + request: compute.InsertInstantSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the insert method over HTTP. + + Args: + request (~.compute.InsertInstantSnapshotRequest): + The request object. A request message for + InstantSnapshots.Insert. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.Operation: + Represents an Operation resource. Google Compute Engine + has three Operation resources: \* + `Global `__ + \* + `Regional `__ + \* + `Zonal `__ + You can use an operation resource to manage asynchronous + API requests. For more information, read Handling API + responses. Operations can be global, regional or zonal. + - For global operations, use the ``globalOperations`` + resource. - For regional operations, use the + ``regionOperations`` resource. - For zonal operations, + use the ``zoneOperations`` resource. For more + information, read Global, Regional, and Zonal Resources. + Note that completed Operation resources have a limited + retention period. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/zones/{zone}/instantSnapshots", + "body": "instant_snapshot_resource", + }, + ] + request, metadata = self._interceptor.pre_insert(request, metadata) + pb_request = compute.InsertInstantSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_insert(resp) + return resp + + class _List(InstantSnapshotsRestStub): + def __hash__(self): + return hash("List") + + __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 + } + + def __call__( + self, + request: compute.ListInstantSnapshotsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.InstantSnapshotList: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListInstantSnapshotsRequest): + The request object. A request message for + InstantSnapshots.List. See the method + description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.InstantSnapshotList: + Contains a list of InstantSnapshot + resources. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/zones/{zone}/instantSnapshots", + }, + ] + request, metadata = self._interceptor.pre_list(request, metadata) + pb_request = compute.ListInstantSnapshotsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.InstantSnapshotList() + pb_resp = compute.InstantSnapshotList.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list(resp) + return resp + + class _SetIamPolicy(InstantSnapshotsRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __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 + } + + def __call__( + self, + request: compute.SetIamPolicyInstantSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (~.compute.SetIamPolicyInstantSnapshotRequest): + The request object. A request message for + InstantSnapshots.SetIamPolicy. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. A + ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. For some types of Google + Cloud resources, a ``binding`` can also specify a + ``condition``, which is a logical expression that allows + access to a resource only if the expression evaluates to + ``true``. A condition can add constraints based on + attributes of the request, the resource, or both. To + learn which resources support conditions in their IAM + policies, see the `IAM + documentation `__. + **JSON example:** + ``{ "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`` + **YAML example:** + ``bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`` + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/zones/{zone}/instantSnapshots/{resource}/setIamPolicy", + "body": "zone_set_policy_request_resource", + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = compute.SetIamPolicyInstantSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Policy() + pb_resp = compute.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _SetLabels(InstantSnapshotsRestStub): + def __hash__(self): + return hash("SetLabels") + + __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 + } + + def __call__( + self, + request: compute.SetLabelsInstantSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the set labels method over HTTP. + + Args: + request (~.compute.SetLabelsInstantSnapshotRequest): + The request object. A request message for + InstantSnapshots.SetLabels. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.Operation: + Represents an Operation resource. Google Compute Engine + has three Operation resources: \* + `Global `__ + \* + `Regional `__ + \* + `Zonal `__ + You can use an operation resource to manage asynchronous + API requests. For more information, read Handling API + responses. Operations can be global, regional or zonal. + - For global operations, use the ``globalOperations`` + resource. - For regional operations, use the + ``regionOperations`` resource. - For zonal operations, + use the ``zoneOperations`` resource. For more + information, read Global, Regional, and Zonal Resources. + Note that completed Operation resources have a limited + retention period. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/zones/{zone}/instantSnapshots/{resource}/setLabels", + "body": "zone_set_labels_request_resource", + }, + ] + request, metadata = self._interceptor.pre_set_labels(request, metadata) + pb_request = compute.SetLabelsInstantSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_labels(resp) + return resp + + class _TestIamPermissions(InstantSnapshotsRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __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 + } + + def __call__( + self, + request: compute.TestIamPermissionsInstantSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.TestPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (~.compute.TestIamPermissionsInstantSnapshotRequest): + The request object. A request message for + InstantSnapshots.TestIamPermissions. See + the method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.TestPermissionsResponse: + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/zones/{zone}/instantSnapshots/{resource}/testIamPermissions", + "body": "test_permissions_request_resource", + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + pb_request = compute.TestIamPermissionsInstantSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.TestPermissionsResponse() + pb_resp = compute.TestPermissionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def aggregated_list( + self, + ) -> Callable[ + [compute.AggregatedListInstantSnapshotsRequest], + compute.InstantSnapshotAggregatedList, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AggregatedList(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete( + self, + ) -> Callable[[compute.DeleteInstantSnapshotRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Delete(self._session, self._host, self._interceptor) # type: ignore + + @property + def get( + self, + ) -> Callable[[compute.GetInstantSnapshotRequest], compute.InstantSnapshot]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Get(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy( + self, + ) -> Callable[[compute.GetIamPolicyInstantSnapshotRequest], compute.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert( + self, + ) -> Callable[[compute.InsertInstantSnapshotRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Insert(self._session, self._host, self._interceptor) # type: ignore + + @property + def list( + self, + ) -> Callable[[compute.ListInstantSnapshotsRequest], compute.InstantSnapshotList]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._List(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy( + self, + ) -> Callable[[compute.SetIamPolicyInstantSnapshotRequest], compute.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_labels( + self, + ) -> Callable[[compute.SetLabelsInstantSnapshotRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetLabels(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [compute.TestIamPermissionsInstantSnapshotRequest], + compute.TestPermissionsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("InstantSnapshotsRestTransport",) 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 125e75d9c5fa..92fb0848adea 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 @@ -660,8 +660,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of interconnect - attachments. + r"""Retrieves an aggregated list of interconnect attachments. To + prevent failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 fbd004d0c150..fb1370462996 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 @@ -648,7 +648,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of machine types. + r"""Retrieves an aggregated list of machine types. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 97a04f801a1c..0707b05fd3b9 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 @@ -656,9 +656,10 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves the list of all NetworkAttachment - resources, regional and global, available to the - specified project. + r"""Retrieves the list of all NetworkAttachment resources, regional + and global, available to the specified project. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 aa69ed1fe1a6..109d975eabf1 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 @@ -662,8 +662,10 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves the list of all NetworkEdgeSecurityService - resources available to the specified project. + r"""Retrieves the list of all NetworkEdgeSecurityService resources + available to the specified project. To prevent failure, Google + recommends that you set the ``returnPartialSuccess`` parameter + to ``true``. .. code-block:: python 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 95a62a29ec77..1ce118044ee1 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 @@ -658,8 +658,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves the list of network endpoint groups and - sorts them by zone. + r"""Retrieves the list of network endpoint groups and sorts them by + zone. To prevent failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 37e2da3f716a..41386d6e3971 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 @@ -962,9 +962,10 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of node groups. Note: - use nodeGroups.listNodes for more details about each - group. + r"""Retrieves an aggregated list of node groups. Note: use + nodeGroups.listNodes for more details about each group. To + prevent failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 0faf00d15c89..d993dfb9a9a5 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 @@ -654,7 +654,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of node templates. + r"""Retrieves an aggregated list of node templates. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 b328813df2ea..4223d8b5538b 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 @@ -646,7 +646,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of node types. + r"""Retrieves an aggregated list of node types. To prevent failure, + Google recommends that you set the ``returnPartialSuccess`` + parameter to ``true``. .. code-block:: python 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 c417b7497277..fc72b7e923ce 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 @@ -656,7 +656,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of packetMirrorings. + r"""Retrieves an aggregated list of packetMirrorings. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 29a7e90fee60..ca161846f30f 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 @@ -2608,6 +2608,274 @@ def error_code(self): # Done; return the response. return response + def set_cloud_armor_tier_unary( + self, + request: Optional[Union[compute.SetCloudArmorTierProjectRequest, dict]] = None, + *, + project: Optional[str] = None, + projects_set_cloud_armor_tier_request_resource: Optional[ + compute.ProjectsSetCloudArmorTierRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Sets the Cloud Armor tier of the project. To set + ENTERPRISE or above the billing account of the project + must be subscribed to Cloud Armor Enterprise. See + Subscribing to Cloud Armor Enterprise for more + information. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_set_cloud_armor_tier(): + # Create a client + client = compute_v1.ProjectsClient() + + # Initialize request argument(s) + request = compute_v1.SetCloudArmorTierProjectRequest( + project="project_value", + ) + + # Make the request + response = client.set_cloud_armor_tier(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.SetCloudArmorTierProjectRequest, dict]): + The request object. A request message for + Projects.SetCloudArmorTier. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + projects_set_cloud_armor_tier_request_resource (google.cloud.compute_v1.types.ProjectsSetCloudArmorTierRequest): + The body resource for this request + This corresponds to the ``projects_set_cloud_armor_tier_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any( + [project, projects_set_cloud_armor_tier_request_resource] + ) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.SetCloudArmorTierProjectRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.SetCloudArmorTierProjectRequest): + request = compute.SetCloudArmorTierProjectRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if projects_set_cloud_armor_tier_request_resource is not None: + request.projects_set_cloud_armor_tier_request_resource = ( + projects_set_cloud_armor_tier_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_cloud_armor_tier] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_cloud_armor_tier( + self, + request: Optional[Union[compute.SetCloudArmorTierProjectRequest, dict]] = None, + *, + project: Optional[str] = None, + projects_set_cloud_armor_tier_request_resource: Optional[ + compute.ProjectsSetCloudArmorTierRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Sets the Cloud Armor tier of the project. To set + ENTERPRISE or above the billing account of the project + must be subscribed to Cloud Armor Enterprise. See + Subscribing to Cloud Armor Enterprise for more + information. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_set_cloud_armor_tier(): + # Create a client + client = compute_v1.ProjectsClient() + + # Initialize request argument(s) + request = compute_v1.SetCloudArmorTierProjectRequest( + project="project_value", + ) + + # Make the request + response = client.set_cloud_armor_tier(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.SetCloudArmorTierProjectRequest, dict]): + The request object. A request message for + Projects.SetCloudArmorTier. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + projects_set_cloud_armor_tier_request_resource (google.cloud.compute_v1.types.ProjectsSetCloudArmorTierRequest): + The body resource for this request + This corresponds to the ``projects_set_cloud_armor_tier_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any( + [project, projects_set_cloud_armor_tier_request_resource] + ) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.SetCloudArmorTierProjectRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.SetCloudArmorTierProjectRequest): + request = compute.SetCloudArmorTierProjectRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if projects_set_cloud_armor_tier_request_resource is not None: + request.projects_set_cloud_armor_tier_request_resource = ( + projects_set_cloud_armor_tier_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_cloud_armor_tier] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_operations_client + operation_request = compute.GetGlobalOperationRequest() + operation_request.project = request.project + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + def set_common_instance_metadata_unary( self, request: Optional[ diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/projects/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/projects/transports/base.py index 24e05fc016d1..7f0f71642c09 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/projects/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/projects/transports/base.py @@ -181,6 +181,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.set_cloud_armor_tier: gapic_v1.method.wrap_method( + self.set_cloud_armor_tier, + default_timeout=None, + client_info=client_info, + ), self.set_common_instance_metadata: gapic_v1.method.wrap_method( self.set_common_instance_metadata, default_timeout=None, @@ -298,6 +303,15 @@ def move_instance( ]: raise NotImplementedError() + @property + def set_cloud_armor_tier( + self, + ) -> Callable[ + [compute.SetCloudArmorTierProjectRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def set_common_instance_metadata( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/projects/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/projects/transports/rest.py index 7d5c3d245079..fdd962a68bd1 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/projects/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/projects/transports/rest.py @@ -143,6 +143,14 @@ def post_move_instance(self, response): logging.log(f"Received response: {response}") return response + def pre_set_cloud_armor_tier(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_cloud_armor_tier(self, response): + logging.log(f"Received response: {response}") + return response + def pre_set_common_instance_metadata(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -387,6 +395,29 @@ def post_move_instance(self, response: compute.Operation) -> compute.Operation: """ return response + def pre_set_cloud_armor_tier( + self, + request: compute.SetCloudArmorTierProjectRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.SetCloudArmorTierProjectRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_cloud_armor_tier + + Override in a subclass to manipulate the request or metadata + before they are sent to the Projects server. + """ + return request, metadata + + def post_set_cloud_armor_tier( + self, response: compute.Operation + ) -> compute.Operation: + """Post-rpc interceptor for set_cloud_armor_tier + + Override in a subclass to manipulate the response + after it is returned by the Projects server but before + it is returned to user code. + """ + return response + def pre_set_common_instance_metadata( self, request: compute.SetCommonInstanceMetadataProjectRequest, @@ -1566,6 +1597,117 @@ def __call__( resp = self._interceptor.post_move_instance(resp) return resp + class _SetCloudArmorTier(ProjectsRestStub): + def __hash__(self): + return hash("SetCloudArmorTier") + + __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 + } + + def __call__( + self, + request: compute.SetCloudArmorTierProjectRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the set cloud armor tier method over HTTP. + + Args: + request (~.compute.SetCloudArmorTierProjectRequest): + The request object. A request message for + Projects.SetCloudArmorTier. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.Operation: + Represents an Operation resource. Google Compute Engine + has three Operation resources: \* + `Global `__ + \* + `Regional `__ + \* + `Zonal `__ + You can use an operation resource to manage asynchronous + API requests. For more information, read Handling API + responses. Operations can be global, regional or zonal. + - For global operations, use the ``globalOperations`` + resource. - For regional operations, use the + ``regionOperations`` resource. - For zonal operations, + use the ``zoneOperations`` resource. For more + information, read Global, Regional, and Zonal Resources. + Note that completed Operation resources have a limited + retention period. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/setCloudArmorTier", + "body": "projects_set_cloud_armor_tier_request_resource", + }, + ] + request, metadata = self._interceptor.pre_set_cloud_armor_tier( + request, metadata + ) + pb_request = compute.SetCloudArmorTierProjectRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_cloud_armor_tier(resp) + return resp + class _SetCommonInstanceMetadata(ProjectsRestStub): def __hash__(self): return hash("SetCommonInstanceMetadata") @@ -1980,6 +2122,14 @@ def move_instance( # In C++ this would require a dynamic_cast return self._MoveInstance(self._session, self._host, self._interceptor) # type: ignore + @property + def set_cloud_armor_tier( + self, + ) -> Callable[[compute.SetCloudArmorTierProjectRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetCloudArmorTier(self._session, self._host, self._interceptor) # type: ignore + @property def set_common_instance_metadata( 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 4bf12ee9f949..a471f0620d85 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 @@ -660,8 +660,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Lists all PublicDelegatedPrefix resources owned by - the specific project across all scopes. + r"""Lists all PublicDelegatedPrefix resources owned by the specific + project across all scopes. To prevent failure, Google recommends + that you set the ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 5cda7a766979..7e5f58457006 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 @@ -656,8 +656,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of commitments by - region. + r"""Retrieves an aggregated list of commitments by region. To + prevent failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/__init__.py new file mode 100644 index 000000000000..79d797e8ab83 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import RegionInstantSnapshotsClient + +__all__ = ("RegionInstantSnapshotsClient",) 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 new file mode 100644 index 000000000000..e969431f27cd --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/client.py @@ -0,0 +1,2321 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import os +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import extended_operation, gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import extended_operation # type: ignore + +from google.cloud.compute_v1.services.region_instant_snapshots import pagers +from google.cloud.compute_v1.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, RegionInstantSnapshotsTransport +from .transports.rest import RegionInstantSnapshotsRestTransport + + +class RegionInstantSnapshotsClientMeta(type): + """Metaclass for the RegionInstantSnapshots client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[RegionInstantSnapshotsTransport]] + _transport_registry["rest"] = RegionInstantSnapshotsRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[RegionInstantSnapshotsTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RegionInstantSnapshotsClient(metaclass=RegionInstantSnapshotsClientMeta): + """The RegionInstantSnapshots API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "compute.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "compute.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegionInstantSnapshotsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegionInstantSnapshotsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RegionInstantSnapshotsTransport: + """Returns the transport used by the client instance. + + Returns: + RegionInstantSnapshotsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = RegionInstantSnapshotsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = RegionInstantSnapshotsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + RegionInstantSnapshotsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = RegionInstantSnapshotsClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + 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. + + Returns: + bool: True iff the configured universe domain is valid. + + 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 + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RegionInstantSnapshotsTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the region instant snapshots client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, RegionInstantSnapshotsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = RegionInstantSnapshotsClient._read_environment_variables() + self._client_cert_source = RegionInstantSnapshotsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = RegionInstantSnapshotsClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, RegionInstantSnapshotsTransport) + if transport_provided: + # transport is a RegionInstantSnapshotsTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(RegionInstantSnapshotsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or RegionInstantSnapshotsClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + Transport = type(self).get_transport_class(cast(str, transport)) + self._transport = Transport( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def delete_unary( + self, + request: Optional[ + Union[compute.DeleteRegionInstantSnapshotRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + instant_snapshot: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Deletes the specified InstantSnapshot resource. Keep + in mind that deleting a single instantSnapshot might not + necessarily delete all the data on that instantSnapshot. + If any data on the instantSnapshot that is marked for + deletion is needed for subsequent instantSnapshots, the + data will be moved to the next corresponding + instantSnapshot. For more information, see Deleting + instantSnapshots. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_delete(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.DeleteRegionInstantSnapshotRequest( + instant_snapshot="instant_snapshot_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.DeleteRegionInstantSnapshotRequest, dict]): + The request object. A request message for + RegionInstantSnapshots.Delete. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instant_snapshot (str): + Name of the InstantSnapshot resource + to delete. + + This corresponds to the ``instant_snapshot`` 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.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, region, instant_snapshot]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.DeleteRegionInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.DeleteRegionInstantSnapshotRequest): + request = compute.DeleteRegionInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if instant_snapshot is not None: + request.instant_snapshot = instant_snapshot + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ("instant_snapshot", request.instant_snapshot), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete( + self, + request: Optional[ + Union[compute.DeleteRegionInstantSnapshotRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + instant_snapshot: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Deletes the specified InstantSnapshot resource. Keep + in mind that deleting a single instantSnapshot might not + necessarily delete all the data on that instantSnapshot. + If any data on the instantSnapshot that is marked for + deletion is needed for subsequent instantSnapshots, the + data will be moved to the next corresponding + instantSnapshot. For more information, see Deleting + instantSnapshots. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_delete(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.DeleteRegionInstantSnapshotRequest( + instant_snapshot="instant_snapshot_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.DeleteRegionInstantSnapshotRequest, dict]): + The request object. A request message for + RegionInstantSnapshots.Delete. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instant_snapshot (str): + Name of the InstantSnapshot resource + to delete. + + This corresponds to the ``instant_snapshot`` 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.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, region, instant_snapshot]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.DeleteRegionInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.DeleteRegionInstantSnapshotRequest): + request = compute.DeleteRegionInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if instant_snapshot is not None: + request.instant_snapshot = instant_snapshot + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ("instant_snapshot", request.instant_snapshot), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def get( + self, + request: Optional[Union[compute.GetRegionInstantSnapshotRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + instant_snapshot: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.InstantSnapshot: + r"""Returns the specified InstantSnapshot resource in the + specified region. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_get(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.GetRegionInstantSnapshotRequest( + instant_snapshot="instant_snapshot_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.GetRegionInstantSnapshotRequest, dict]): + The request object. A request message for + RegionInstantSnapshots.Get. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instant_snapshot (str): + Name of the InstantSnapshot resource + to return. + + This corresponds to the ``instant_snapshot`` 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.compute_v1.types.InstantSnapshot: + Represents a InstantSnapshot + resource. You can use instant snapshots + to create disk rollback points quickly.. + + """ + # 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([project, region, instant_snapshot]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.GetRegionInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.GetRegionInstantSnapshotRequest): + request = compute.GetRegionInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if instant_snapshot is not None: + request.instant_snapshot = instant_snapshot + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ("instant_snapshot", request.instant_snapshot), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[ + Union[compute.GetIamPolicyRegionInstantSnapshotRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Policy: + r"""Gets the access control policy for a resource. May be + empty if no such policy or resource exists. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_get_iam_policy(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.GetIamPolicyRegionInstantSnapshotRequest( + project="project_value", + region="region_value", + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.GetIamPolicyRegionInstantSnapshotRequest, dict]): + The request object. A request message for + RegionInstantSnapshots.GetIamPolicy. See + the method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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.compute_v1.types.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. A + Policy is a collection of bindings. A binding binds one + or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role is + a named list of permissions; each role can be an IAM + predefined role or a user-created custom role. For some + types of Google Cloud resources, a binding can also + specify a condition, which is a logical expression that + allows access to a resource only if the expression + evaluates to true. A condition can add constraints based + on attributes of the request, the resource, or both. To + learn which resources support conditions in their IAM + policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + **JSON example:** + :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + **YAML example:** + :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + For a description of IAM and its features, see the [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, region, resource]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.GetIamPolicyRegionInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.GetIamPolicyRegionInstantSnapshotRequest): + request = compute.GetIamPolicyRegionInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ("resource", request.resource), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert_unary( + self, + request: Optional[ + Union[compute.InsertRegionInstantSnapshotRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + instant_snapshot_resource: Optional[compute.InstantSnapshot] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Creates an instant snapshot in the specified region. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_insert(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.InsertRegionInstantSnapshotRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.InsertRegionInstantSnapshotRequest, dict]): + The request object. A request message for + RegionInstantSnapshots.Insert. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + Name of the region for this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instant_snapshot_resource (google.cloud.compute_v1.types.InstantSnapshot): + The body resource for this request + This corresponds to the ``instant_snapshot_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, region, instant_snapshot_resource]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.InsertRegionInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.InsertRegionInstantSnapshotRequest): + request = compute.InsertRegionInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if instant_snapshot_resource is not None: + request.instant_snapshot_resource = instant_snapshot_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert( + self, + request: Optional[ + Union[compute.InsertRegionInstantSnapshotRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + instant_snapshot_resource: Optional[compute.InstantSnapshot] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Creates an instant snapshot in the specified region. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_insert(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.InsertRegionInstantSnapshotRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.InsertRegionInstantSnapshotRequest, dict]): + The request object. A request message for + RegionInstantSnapshots.Insert. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + Name of the region for this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instant_snapshot_resource (google.cloud.compute_v1.types.InstantSnapshot): + The body resource for this request + This corresponds to the ``instant_snapshot_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, region, instant_snapshot_resource]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.InsertRegionInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.InsertRegionInstantSnapshotRequest): + request = compute.InsertRegionInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if instant_snapshot_resource is not None: + request.instant_snapshot_resource = instant_snapshot_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def list( + self, + request: Optional[ + Union[compute.ListRegionInstantSnapshotsRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPager: + r"""Retrieves the list of InstantSnapshot resources + contained within the specified region. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_list(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.ListRegionInstantSnapshotsRequest( + project="project_value", + region="region_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.ListRegionInstantSnapshotsRequest, dict]): + The request object. A request message for + RegionInstantSnapshots.List. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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.compute_v1.services.region_instant_snapshots.pagers.ListPager: + Contains a list of InstantSnapshot + resources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([project, region]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.ListRegionInstantSnapshotsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.ListRegionInstantSnapshotsRequest): + request = compute.ListRegionInstantSnapshotsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: Optional[ + Union[compute.SetIamPolicyRegionInstantSnapshotRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + resource: Optional[str] = None, + region_set_policy_request_resource: Optional[ + compute.RegionSetPolicyRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Policy: + r"""Sets the access control policy on the specified + resource. Replaces any existing policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_set_iam_policy(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.SetIamPolicyRegionInstantSnapshotRequest( + project="project_value", + region="region_value", + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.SetIamPolicyRegionInstantSnapshotRequest, dict]): + The request object. A request message for + RegionInstantSnapshots.SetIamPolicy. See + the method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region_set_policy_request_resource (google.cloud.compute_v1.types.RegionSetPolicyRequest): + The body resource for this request + This corresponds to the ``region_set_policy_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. A + Policy is a collection of bindings. A binding binds one + or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role is + a named list of permissions; each role can be an IAM + predefined role or a user-created custom role. For some + types of Google Cloud resources, a binding can also + specify a condition, which is a logical expression that + allows access to a resource only if the expression + evaluates to true. A condition can add constraints based + on attributes of the request, the resource, or both. To + learn which resources support conditions in their IAM + policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + **JSON example:** + :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + **YAML example:** + :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + For a description of IAM and its features, see the [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any( + [project, region, resource, region_set_policy_request_resource] + ) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.SetIamPolicyRegionInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.SetIamPolicyRegionInstantSnapshotRequest): + request = compute.SetIamPolicyRegionInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if resource is not None: + request.resource = resource + if region_set_policy_request_resource is not None: + request.region_set_policy_request_resource = ( + region_set_policy_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ("resource", request.resource), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_labels_unary( + self, + request: Optional[ + Union[compute.SetLabelsRegionInstantSnapshotRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + resource: Optional[str] = None, + region_set_labels_request_resource: Optional[ + compute.RegionSetLabelsRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Sets the labels on a instantSnapshot in the given + region. To learn more about labels, read the Labeling + Resources documentation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_set_labels(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.SetLabelsRegionInstantSnapshotRequest( + project="project_value", + region="region_value", + resource="resource_value", + ) + + # Make the request + response = client.set_labels(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.SetLabelsRegionInstantSnapshotRequest, dict]): + The request object. A request message for + RegionInstantSnapshots.SetLabels. See + the method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + The region for this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region_set_labels_request_resource (google.cloud.compute_v1.types.RegionSetLabelsRequest): + The body resource for this request + This corresponds to the ``region_set_labels_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any( + [project, region, resource, region_set_labels_request_resource] + ) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.SetLabelsRegionInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.SetLabelsRegionInstantSnapshotRequest): + request = compute.SetLabelsRegionInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if resource is not None: + request.resource = resource + if region_set_labels_request_resource is not None: + request.region_set_labels_request_resource = ( + region_set_labels_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_labels] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ("resource", request.resource), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_labels( + self, + request: Optional[ + Union[compute.SetLabelsRegionInstantSnapshotRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + resource: Optional[str] = None, + region_set_labels_request_resource: Optional[ + compute.RegionSetLabelsRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Sets the labels on a instantSnapshot in the given + region. To learn more about labels, read the Labeling + Resources documentation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_set_labels(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.SetLabelsRegionInstantSnapshotRequest( + project="project_value", + region="region_value", + resource="resource_value", + ) + + # Make the request + response = client.set_labels(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.SetLabelsRegionInstantSnapshotRequest, dict]): + The request object. A request message for + RegionInstantSnapshots.SetLabels. See + the method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + The region for this request. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region_set_labels_request_resource (google.cloud.compute_v1.types.RegionSetLabelsRequest): + The body resource for this request + This corresponds to the ``region_set_labels_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any( + [project, region, resource, region_set_labels_request_resource] + ) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.SetLabelsRegionInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, compute.SetLabelsRegionInstantSnapshotRequest): + request = compute.SetLabelsRegionInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if resource is not None: + request.resource = resource + if region_set_labels_request_resource is not None: + request.region_set_labels_request_resource = ( + region_set_labels_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_labels] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ("resource", request.resource), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[ + Union[compute.TestIamPermissionsRegionInstantSnapshotRequest, dict] + ] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + resource: Optional[str] = None, + test_permissions_request_resource: Optional[ + compute.TestPermissionsRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.TestPermissionsResponse: + r"""Returns permissions that a caller has on the + specified resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_test_iam_permissions(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.TestIamPermissionsRegionInstantSnapshotRequest( + project="project_value", + region="region_value", + resource="resource_value", + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.TestIamPermissionsRegionInstantSnapshotRequest, dict]): + The request object. A request message for + RegionInstantSnapshots.TestIamPermissions. + See the method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + The name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource (str): + Name or id of the resource for this + request. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + test_permissions_request_resource (google.cloud.compute_v1.types.TestPermissionsRequest): + The body resource for this request + This corresponds to the ``test_permissions_request_resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.compute_v1.types.TestPermissionsResponse: + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any( + [project, region, resource, test_permissions_request_resource] + ) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a compute.TestIamPermissionsRegionInstantSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, compute.TestIamPermissionsRegionInstantSnapshotRequest + ): + request = compute.TestIamPermissionsRegionInstantSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if resource is not None: + request.resource = resource + if test_permissions_request_resource is not None: + request.test_permissions_request_resource = ( + test_permissions_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("region", request.region), + ("resource", request.resource), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "RegionInstantSnapshotsClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("RegionInstantSnapshotsClient",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/pagers.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/pagers.py new file mode 100644 index 000000000000..e6e0043153bc --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/pagers.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.compute_v1.types import compute + + +class ListPager: + """A pager for iterating through ``list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.compute_v1.types.InstantSnapshotList` object, and + provides an ``__iter__`` method to iterate through its + ``items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``List`` requests and continue to iterate + through the ``items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.compute_v1.types.InstantSnapshotList` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., compute.InstantSnapshotList], + request: compute.ListRegionInstantSnapshotsRequest, + response: compute.InstantSnapshotList, + *, + 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.compute_v1.types.ListRegionInstantSnapshotsRequest): + The initial request object. + response (google.cloud.compute_v1.types.InstantSnapshotList): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = compute.ListRegionInstantSnapshotsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[compute.InstantSnapshotList]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[compute.InstantSnapshot]: + for page in self.pages: + yield from page.items + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/transports/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/transports/__init__.py new file mode 100644 index 000000000000..5bac4216e1b9 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/transports/__init__.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import RegionInstantSnapshotsTransport +from .rest import ( + RegionInstantSnapshotsRestInterceptor, + RegionInstantSnapshotsRestTransport, +) + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[RegionInstantSnapshotsTransport]] +_transport_registry["rest"] = RegionInstantSnapshotsRestTransport + +__all__ = ( + "RegionInstantSnapshotsTransport", + "RegionInstantSnapshotsRestTransport", + "RegionInstantSnapshotsRestInterceptor", +) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/transports/base.py new file mode 100644 index 000000000000..198a469fe672 --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/transports/base.py @@ -0,0 +1,276 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1 import gapic_version as package_version +from google.cloud.compute_v1.services import region_operations +from google.cloud.compute_v1.types import compute + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class RegionInstantSnapshotsTransport(abc.ABC): + """Abstract transport class for RegionInstantSnapshots.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "compute.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + self._extended_operations_services: Dict[str, Any] = {} + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.delete: gapic_v1.method.wrap_method( + self.delete, + default_timeout=None, + client_info=client_info, + ), + self.get: gapic_v1.method.wrap_method( + self.get, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.insert: gapic_v1.method.wrap_method( + self.insert, + default_timeout=None, + client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_labels: gapic_v1.method.wrap_method( + self.set_labels, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def delete( + self, + ) -> Callable[ + [compute.DeleteRegionInstantSnapshotRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetRegionInstantSnapshotRequest], + Union[compute.InstantSnapshot, Awaitable[compute.InstantSnapshot]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [compute.GetIamPolicyRegionInstantSnapshotRequest], + Union[compute.Policy, Awaitable[compute.Policy]], + ]: + raise NotImplementedError() + + @property + def insert( + self, + ) -> Callable[ + [compute.InsertRegionInstantSnapshotRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListRegionInstantSnapshotsRequest], + Union[compute.InstantSnapshotList, Awaitable[compute.InstantSnapshotList]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [compute.SetIamPolicyRegionInstantSnapshotRequest], + Union[compute.Policy, Awaitable[compute.Policy]], + ]: + raise NotImplementedError() + + @property + def set_labels( + self, + ) -> Callable[ + [compute.SetLabelsRegionInstantSnapshotRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [compute.TestIamPermissionsRegionInstantSnapshotRequest], + Union[ + compute.TestPermissionsResponse, Awaitable[compute.TestPermissionsResponse] + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + @property + def _region_operations_client(self) -> region_operations.RegionOperationsClient: + ex_op_service = self._extended_operations_services.get("region_operations") + if not ex_op_service: + ex_op_service = region_operations.RegionOperationsClient( + credentials=self._credentials, + transport=self.kind, + ) + self._extended_operations_services["region_operations"] = ex_op_service + + return ex_op_service + + +__all__ = ("RegionInstantSnapshotsTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/transports/rest.py new file mode 100644 index 000000000000..f7c7aa88e56c --- /dev/null +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_instant_snapshots/transports/rest.py @@ -0,0 +1,1312 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.cloud.compute_v1.types import compute + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import RegionInstantSnapshotsTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class RegionInstantSnapshotsRestInterceptor: + """Interceptor for RegionInstantSnapshots. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the RegionInstantSnapshotsRestTransport. + + .. code-block:: python + class MyCustomRegionInstantSnapshotsInterceptor(RegionInstantSnapshotsRestInterceptor): + def pre_delete(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_insert(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_labels(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_labels(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RegionInstantSnapshotsRestTransport(interceptor=MyCustomRegionInstantSnapshotsInterceptor()) + client = RegionInstantSnapshotsClient(transport=transport) + + + """ + + def pre_delete( + self, + request: compute.DeleteRegionInstantSnapshotRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.DeleteRegionInstantSnapshotRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionInstantSnapshots server. + """ + return request, metadata + + def post_delete(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for delete + + Override in a subclass to manipulate the response + after it is returned by the RegionInstantSnapshots server but before + it is returned to user code. + """ + return response + + def pre_get( + self, + request: compute.GetRegionInstantSnapshotRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.GetRegionInstantSnapshotRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionInstantSnapshots server. + """ + return request, metadata + + def post_get(self, response: compute.InstantSnapshot) -> compute.InstantSnapshot: + """Post-rpc interceptor for get + + Override in a subclass to manipulate the response + after it is returned by the RegionInstantSnapshots server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: compute.GetIamPolicyRegionInstantSnapshotRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + compute.GetIamPolicyRegionInstantSnapshotRequest, 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 RegionInstantSnapshots server. + """ + return request, metadata + + def post_get_iam_policy(self, response: compute.Policy) -> compute.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the RegionInstantSnapshots server but before + it is returned to user code. + """ + return response + + def pre_insert( + self, + request: compute.InsertRegionInstantSnapshotRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.InsertRegionInstantSnapshotRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for insert + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionInstantSnapshots server. + """ + return request, metadata + + def post_insert(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for insert + + Override in a subclass to manipulate the response + after it is returned by the RegionInstantSnapshots server but before + it is returned to user code. + """ + return response + + def pre_list( + self, + request: compute.ListRegionInstantSnapshotsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[compute.ListRegionInstantSnapshotsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionInstantSnapshots server. + """ + return request, metadata + + def post_list( + self, response: compute.InstantSnapshotList + ) -> compute.InstantSnapshotList: + """Post-rpc interceptor for list + + Override in a subclass to manipulate the response + after it is returned by the RegionInstantSnapshots server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: compute.SetIamPolicyRegionInstantSnapshotRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + compute.SetIamPolicyRegionInstantSnapshotRequest, 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 RegionInstantSnapshots server. + """ + return request, metadata + + def post_set_iam_policy(self, response: compute.Policy) -> compute.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the RegionInstantSnapshots server but before + it is returned to user code. + """ + return response + + def pre_set_labels( + self, + request: compute.SetLabelsRegionInstantSnapshotRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + compute.SetLabelsRegionInstantSnapshotRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for set_labels + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionInstantSnapshots server. + """ + return request, metadata + + def post_set_labels(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for set_labels + + Override in a subclass to manipulate the response + after it is returned by the RegionInstantSnapshots server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: compute.TestIamPermissionsRegionInstantSnapshotRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + compute.TestIamPermissionsRegionInstantSnapshotRequest, + 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 RegionInstantSnapshots server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: compute.TestPermissionsResponse + ) -> compute.TestPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the RegionInstantSnapshots server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class RegionInstantSnapshotsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RegionInstantSnapshotsRestInterceptor + + +class RegionInstantSnapshotsRestTransport(RegionInstantSnapshotsTransport): + """REST backend transport for RegionInstantSnapshots. + + The RegionInstantSnapshots API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via an issue in this + library's source repository. Thank you! + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[RegionInstantSnapshotsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): 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 + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or RegionInstantSnapshotsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Delete(RegionInstantSnapshotsRestStub): + def __hash__(self): + return hash("Delete") + + __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 + } + + def __call__( + self, + request: compute.DeleteRegionInstantSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the delete method over HTTP. + + Args: + request (~.compute.DeleteRegionInstantSnapshotRequest): + The request object. A request message for + RegionInstantSnapshots.Delete. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.Operation: + Represents an Operation resource. Google Compute Engine + has three Operation resources: \* + `Global `__ + \* + `Regional `__ + \* + `Zonal `__ + You can use an operation resource to manage asynchronous + API requests. For more information, read Handling API + responses. Operations can be global, regional or zonal. + - For global operations, use the ``globalOperations`` + resource. - For regional operations, use the + ``regionOperations`` resource. - For zonal operations, + use the ``zoneOperations`` resource. For more + information, read Global, Regional, and Zonal Resources. + Note that completed Operation resources have a limited + retention period. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/compute/v1/projects/{project}/regions/{region}/instantSnapshots/{instant_snapshot}", + }, + ] + request, metadata = self._interceptor.pre_delete(request, metadata) + pb_request = compute.DeleteRegionInstantSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete(resp) + return resp + + class _Get(RegionInstantSnapshotsRestStub): + def __hash__(self): + return hash("Get") + + __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 + } + + def __call__( + self, + request: compute.GetRegionInstantSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.InstantSnapshot: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetRegionInstantSnapshotRequest): + The request object. A request message for + RegionInstantSnapshots.Get. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.InstantSnapshot: + Represents a InstantSnapshot + resource. You can use instant snapshots + to create disk rollback points quickly.. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/regions/{region}/instantSnapshots/{instant_snapshot}", + }, + ] + request, metadata = self._interceptor.pre_get(request, metadata) + pb_request = compute.GetRegionInstantSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.InstantSnapshot() + pb_resp = compute.InstantSnapshot.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get(resp) + return resp + + class _GetIamPolicy(RegionInstantSnapshotsRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __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 + } + + def __call__( + self, + request: compute.GetIamPolicyRegionInstantSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (~.compute.GetIamPolicyRegionInstantSnapshotRequest): + The request object. A request message for + RegionInstantSnapshots.GetIamPolicy. See + the method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. A + ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. For some types of Google + Cloud resources, a ``binding`` can also specify a + ``condition``, which is a logical expression that allows + access to a resource only if the expression evaluates to + ``true``. A condition can add constraints based on + attributes of the request, the resource, or both. To + learn which resources support conditions in their IAM + policies, see the `IAM + documentation `__. + **JSON example:** + ``{ "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`` + **YAML example:** + ``bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`` + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/regions/{region}/instantSnapshots/{resource}/getIamPolicy", + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = compute.GetIamPolicyRegionInstantSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Policy() + pb_resp = compute.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _Insert(RegionInstantSnapshotsRestStub): + def __hash__(self): + return hash("Insert") + + __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 + } + + def __call__( + self, + request: compute.InsertRegionInstantSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the insert method over HTTP. + + Args: + request (~.compute.InsertRegionInstantSnapshotRequest): + The request object. A request message for + RegionInstantSnapshots.Insert. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.Operation: + Represents an Operation resource. Google Compute Engine + has three Operation resources: \* + `Global `__ + \* + `Regional `__ + \* + `Zonal `__ + You can use an operation resource to manage asynchronous + API requests. For more information, read Handling API + responses. Operations can be global, regional or zonal. + - For global operations, use the ``globalOperations`` + resource. - For regional operations, use the + ``regionOperations`` resource. - For zonal operations, + use the ``zoneOperations`` resource. For more + information, read Global, Regional, and Zonal Resources. + Note that completed Operation resources have a limited + retention period. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/regions/{region}/instantSnapshots", + "body": "instant_snapshot_resource", + }, + ] + request, metadata = self._interceptor.pre_insert(request, metadata) + pb_request = compute.InsertRegionInstantSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_insert(resp) + return resp + + class _List(RegionInstantSnapshotsRestStub): + def __hash__(self): + return hash("List") + + __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 + } + + def __call__( + self, + request: compute.ListRegionInstantSnapshotsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.InstantSnapshotList: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListRegionInstantSnapshotsRequest): + The request object. A request message for + RegionInstantSnapshots.List. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.InstantSnapshotList: + Contains a list of InstantSnapshot + resources. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/v1/projects/{project}/regions/{region}/instantSnapshots", + }, + ] + request, metadata = self._interceptor.pre_list(request, metadata) + pb_request = compute.ListRegionInstantSnapshotsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.InstantSnapshotList() + pb_resp = compute.InstantSnapshotList.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list(resp) + return resp + + class _SetIamPolicy(RegionInstantSnapshotsRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __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 + } + + def __call__( + self, + request: compute.SetIamPolicyRegionInstantSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (~.compute.SetIamPolicyRegionInstantSnapshotRequest): + The request object. A request message for + RegionInstantSnapshots.SetIamPolicy. See + the method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. A + ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. For some types of Google + Cloud resources, a ``binding`` can also specify a + ``condition``, which is a logical expression that allows + access to a resource only if the expression evaluates to + ``true``. A condition can add constraints based on + attributes of the request, the resource, or both. To + learn which resources support conditions in their IAM + policies, see the `IAM + documentation `__. + **JSON example:** + ``{ "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`` + **YAML example:** + ``bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`` + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/regions/{region}/instantSnapshots/{resource}/setIamPolicy", + "body": "region_set_policy_request_resource", + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = compute.SetIamPolicyRegionInstantSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Policy() + pb_resp = compute.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _SetLabels(RegionInstantSnapshotsRestStub): + def __hash__(self): + return hash("SetLabels") + + __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 + } + + def __call__( + self, + request: compute.SetLabelsRegionInstantSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.Operation: + r"""Call the set labels method over HTTP. + + Args: + request (~.compute.SetLabelsRegionInstantSnapshotRequest): + The request object. A request message for + RegionInstantSnapshots.SetLabels. See + the method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.Operation: + Represents an Operation resource. Google Compute Engine + has three Operation resources: \* + `Global `__ + \* + `Regional `__ + \* + `Zonal `__ + You can use an operation resource to manage asynchronous + API requests. For more information, read Handling API + responses. Operations can be global, regional or zonal. + - For global operations, use the ``globalOperations`` + resource. - For regional operations, use the + ``regionOperations`` resource. - For zonal operations, + use the ``zoneOperations`` resource. For more + information, read Global, Regional, and Zonal Resources. + Note that completed Operation resources have a limited + retention period. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/regions/{region}/instantSnapshots/{resource}/setLabels", + "body": "region_set_labels_request_resource", + }, + ] + request, metadata = self._interceptor.pre_set_labels(request, metadata) + pb_request = compute.SetLabelsRegionInstantSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_labels(resp) + return resp + + class _TestIamPermissions(RegionInstantSnapshotsRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __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 + } + + def __call__( + self, + request: compute.TestIamPermissionsRegionInstantSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> compute.TestPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (~.compute.TestIamPermissionsRegionInstantSnapshotRequest): + The request object. A request message for + RegionInstantSnapshots.TestIamPermissions. + See the method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.compute.TestPermissionsResponse: + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/regions/{region}/instantSnapshots/{resource}/testIamPermissions", + "body": "test_permissions_request_resource", + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + pb_request = compute.TestIamPermissionsRegionInstantSnapshotRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.TestPermissionsResponse() + pb_resp = compute.TestPermissionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def delete( + self, + ) -> Callable[[compute.DeleteRegionInstantSnapshotRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Delete(self._session, self._host, self._interceptor) # type: ignore + + @property + def get( + self, + ) -> Callable[[compute.GetRegionInstantSnapshotRequest], compute.InstantSnapshot]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Get(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy( + self, + ) -> Callable[[compute.GetIamPolicyRegionInstantSnapshotRequest], compute.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert( + self, + ) -> Callable[[compute.InsertRegionInstantSnapshotRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Insert(self._session, self._host, self._interceptor) # type: ignore + + @property + def list( + self, + ) -> Callable[ + [compute.ListRegionInstantSnapshotsRequest], compute.InstantSnapshotList + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._List(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy( + self, + ) -> Callable[[compute.SetIamPolicyRegionInstantSnapshotRequest], compute.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_labels( + self, + ) -> Callable[[compute.SetLabelsRegionInstantSnapshotRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetLabels(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [compute.TestIamPermissionsRegionInstantSnapshotRequest], + compute.TestPermissionsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("RegionInstantSnapshotsRestTransport",) 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 3a6ee2026a2f..1f531e23d520 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 @@ -651,7 +651,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of reservations. + r"""Retrieves an aggregated list of reservations. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 e9a8c172d28f..f5ce218d96b8 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 @@ -656,7 +656,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of resource policies. + r"""Retrieves an aggregated list of resource policies. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 6e68c9808d22..6b6f03118df1 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 @@ -649,7 +649,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of routers. + r"""Retrieves an aggregated list of routers. To prevent failure, + Google recommends that you set the ``returnPartialSuccess`` + parameter to ``true``. .. code-block:: python 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 10ae8c259a27..9a179672ebc9 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 @@ -940,8 +940,10 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves the list of all SecurityPolicy resources, - regional and global, available to the specified project. + r"""Retrieves the list of all SecurityPolicy resources, regional and + global, available to the specified project. To prevent failure, + Google recommends that you set the ``returnPartialSuccess`` + parameter to ``true``. .. code-block:: python 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 ad1a72a321c9..aaca939daa68 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 @@ -656,9 +656,10 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves the list of all ServiceAttachment - resources, regional and global, available to the - specified project. + r"""Retrieves the list of all ServiceAttachment resources, regional + and global, available to the specified project. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 5f509cad70f0..e51ad150498d 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 @@ -656,8 +656,10 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves the list of all SslCertificate resources, - regional and global, available to the specified project. + r"""Retrieves the list of all SslCertificate resources, regional and + global, available to the specified project. To prevent failure, + Google recommends that you set the ``returnPartialSuccess`` + parameter to ``true``. .. code-block:: python 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 3b0bef738566..93b1f5bb3449 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 @@ -649,8 +649,10 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves the list of all SslPolicy resources, - regional and global, available to the specified project. + r"""Retrieves the list of all SslPolicy resources, regional and + global, available to the specified project. To prevent failure, + Google recommends that you set the ``returnPartialSuccess`` + parameter to ``true``. .. code-block:: python 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 928f68fc11dc..c26e735f3cd6 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 @@ -649,7 +649,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of subnetworks. + r"""Retrieves an aggregated list of subnetworks. To prevent failure, + Google recommends that you set the ``returnPartialSuccess`` + parameter to ``true``. .. code-block:: python 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 b95fc1a0b048..646e1b3d8e20 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 @@ -656,8 +656,10 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves the list of all TargetHttpProxy resources, - regional and global, available to the specified project. + r"""Retrieves the list of all TargetHttpProxy resources, regional + and global, available to the specified project. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 07311f0958b1..0ece65f2cee9 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 @@ -656,8 +656,10 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves the list of all TargetHttpsProxy resources, - regional and global, available to the specified project. + r"""Retrieves the list of all TargetHttpsProxy resources, regional + and global, available to the specified project. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 7e36eb483f8e..07e12ad2da9e 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 @@ -656,7 +656,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of target instances. + r"""Retrieves an aggregated list of target instances. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 25e929b62269..3f532256e266 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 @@ -1293,7 +1293,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of target pools. + r"""Retrieves an aggregated list of target pools. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 23d6f365d728..2519a4fc4fad 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 @@ -656,8 +656,10 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves the list of all TargetTcpProxy resources, - regional and global, available to the specified project. + r"""Retrieves the list of all TargetTcpProxy resources, regional and + global, available to the specified project. To prevent failure, + Google recommends that you set the ``returnPartialSuccess`` + parameter to ``true``. .. code-block:: python 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 6928fe665006..03e6a0f1e87c 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 @@ -656,7 +656,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of target VPN gateways. + r"""Retrieves an aggregated list of target VPN gateways. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 e114fcb6a05f..4532a8dd8d93 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 @@ -649,8 +649,10 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves the list of all UrlMap resources, regional - and global, available to the specified project. + r"""Retrieves the list of all UrlMap resources, regional and global, + available to the specified project. To prevent failure, Google + recommends that you set the ``returnPartialSuccess`` parameter + to ``true``. .. code-block:: python 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 05ea67388990..4054ba4e3707 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 @@ -649,7 +649,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of VPN gateways. + r"""Retrieves an aggregated list of VPN gateways. To prevent + failure, Google recommends that you set the + ``returnPartialSuccess`` parameter to ``true``. .. code-block:: python 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 748a1a5ffad6..faa6b2755e23 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 @@ -649,7 +649,9 @@ def aggregated_list( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: - r"""Retrieves an aggregated list of VPN tunnels. + r"""Retrieves an aggregated list of VPN tunnels. To prevent failure, + Google recommends that you set the ``returnPartialSuccess`` + parameter to ``true``. .. code-block:: python diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py index f340df05c708..2907d172c7a0 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py @@ -60,6 +60,7 @@ AggregatedListInstanceGroupsRequest, AggregatedListInstancesRequest, AggregatedListInstanceTemplatesRequest, + AggregatedListInstantSnapshotsRequest, AggregatedListInterconnectAttachmentsRequest, AggregatedListMachineTypesRequest, AggregatedListNetworkAttachmentsRequest, @@ -209,6 +210,7 @@ DeleteInstancesInstanceGroupManagerRequest, DeleteInstancesRegionInstanceGroupManagerRequest, DeleteInstanceTemplateRequest, + DeleteInstantSnapshotRequest, DeleteInterconnectAttachmentRequest, DeleteInterconnectRequest, DeleteLicenseRequest, @@ -233,6 +235,7 @@ DeleteRegionHealthCheckServiceRequest, DeleteRegionInstanceGroupManagerRequest, DeleteRegionInstanceTemplateRequest, + DeleteRegionInstantSnapshotRequest, DeleteRegionNetworkEndpointGroupRequest, DeleteRegionNetworkFirewallPolicyRequest, DeleteRegionNotificationEndpointRequest, @@ -372,6 +375,7 @@ GetIamPolicyImageRequest, GetIamPolicyInstanceRequest, GetIamPolicyInstanceTemplateRequest, + GetIamPolicyInstantSnapshotRequest, GetIamPolicyLicenseRequest, GetIamPolicyMachineImageRequest, GetIamPolicyNetworkAttachmentRequest, @@ -380,6 +384,7 @@ GetIamPolicyNodeTemplateRequest, GetIamPolicyRegionBackendServiceRequest, GetIamPolicyRegionDiskRequest, + GetIamPolicyRegionInstantSnapshotRequest, GetIamPolicyRegionNetworkFirewallPolicyRequest, GetIamPolicyReservationRequest, GetIamPolicyResourcePolicyRequest, @@ -392,6 +397,7 @@ GetInstanceGroupRequest, GetInstanceRequest, GetInstanceTemplateRequest, + GetInstantSnapshotRequest, GetInterconnectAttachmentRequest, GetInterconnectLocationRequest, GetInterconnectRemoteLocationRequest, @@ -425,6 +431,7 @@ GetRegionInstanceGroupManagerRequest, GetRegionInstanceGroupRequest, GetRegionInstanceTemplateRequest, + GetRegionInstantSnapshotRequest, GetRegionNetworkEndpointGroupRequest, GetRegionNetworkFirewallPolicyRequest, GetRegionNotificationEndpointRequest, @@ -536,6 +543,7 @@ InsertInstanceGroupRequest, InsertInstanceRequest, InsertInstanceTemplateRequest, + InsertInstantSnapshotRequest, InsertInterconnectAttachmentRequest, InsertInterconnectRequest, InsertLicenseRequest, @@ -558,6 +566,7 @@ InsertRegionHealthCheckServiceRequest, InsertRegionInstanceGroupManagerRequest, InsertRegionInstanceTemplateRequest, + InsertRegionInstantSnapshotRequest, InsertRegionNetworkEndpointGroupRequest, InsertRegionNetworkFirewallPolicyRequest, InsertRegionNotificationEndpointRequest, @@ -659,6 +668,11 @@ InstanceTemplateList, InstanceTemplatesScopedList, InstanceWithNamedPorts, + InstantSnapshot, + InstantSnapshotAggregatedList, + InstantSnapshotList, + InstantSnapshotResourceStatus, + InstantSnapshotsScopedList, Int64RangeMatch, Interconnect, InterconnectAttachment, @@ -730,6 +744,7 @@ ListInstancesRegionInstanceGroupsRequest, ListInstancesRequest, ListInstanceTemplatesRequest, + ListInstantSnapshotsRequest, ListInterconnectAttachmentsRequest, ListInterconnectLocationsRequest, ListInterconnectRemoteLocationsRequest, @@ -768,6 +783,7 @@ ListRegionInstanceGroupManagersRequest, ListRegionInstanceGroupsRequest, ListRegionInstanceTemplatesRequest, + ListRegionInstantSnapshotsRequest, ListRegionNetworkEndpointGroupsRequest, ListRegionNetworkFirewallPoliciesRequest, ListRegionNotificationEndpointsRequest, @@ -978,6 +994,7 @@ ProjectsEnableXpnResourceRequest, ProjectsGetXpnResources, ProjectsListXpnHostsRequest, + ProjectsSetCloudArmorTierRequest, ProjectsSetDefaultNetworkTierRequest, PublicAdvertisedPrefix, PublicAdvertisedPrefixList, @@ -1159,6 +1176,7 @@ SetBackupTargetPoolRequest, SetCertificateMapTargetHttpsProxyRequest, SetCertificateMapTargetSslProxyRequest, + SetCloudArmorTierProjectRequest, SetCommonInstanceMetadataOperationMetadata, SetCommonInstanceMetadataOperationMetadataPerLocationOperationInfo, SetCommonInstanceMetadataProjectRequest, @@ -1174,6 +1192,7 @@ SetIamPolicyImageRequest, SetIamPolicyInstanceRequest, SetIamPolicyInstanceTemplateRequest, + SetIamPolicyInstantSnapshotRequest, SetIamPolicyLicenseRequest, SetIamPolicyMachineImageRequest, SetIamPolicyNetworkAttachmentRequest, @@ -1182,6 +1201,7 @@ SetIamPolicyNodeTemplateRequest, SetIamPolicyRegionBackendServiceRequest, SetIamPolicyRegionDiskRequest, + SetIamPolicyRegionInstantSnapshotRequest, SetIamPolicyRegionNetworkFirewallPolicyRequest, SetIamPolicyReservationRequest, SetIamPolicyResourcePolicyRequest, @@ -1198,9 +1218,11 @@ SetLabelsGlobalForwardingRuleRequest, SetLabelsImageRequest, SetLabelsInstanceRequest, + SetLabelsInstantSnapshotRequest, SetLabelsInterconnectAttachmentRequest, SetLabelsInterconnectRequest, SetLabelsRegionDiskRequest, + SetLabelsRegionInstantSnapshotRequest, SetLabelsSecurityPolicyRequest, SetLabelsSnapshotRequest, SetLabelsTargetVpnGatewayRequest, @@ -1350,6 +1372,7 @@ TestIamPermissionsImageRequest, TestIamPermissionsInstanceRequest, TestIamPermissionsInstanceTemplateRequest, + TestIamPermissionsInstantSnapshotRequest, TestIamPermissionsLicenseCodeRequest, TestIamPermissionsLicenseRequest, TestIamPermissionsMachineImageRequest, @@ -1361,6 +1384,7 @@ TestIamPermissionsPacketMirroringRequest, TestIamPermissionsRegionBackendServiceRequest, TestIamPermissionsRegionDiskRequest, + TestIamPermissionsRegionInstantSnapshotRequest, TestIamPermissionsRegionNetworkFirewallPolicyRequest, TestIamPermissionsReservationRequest, TestIamPermissionsResourcePolicyRequest, @@ -1495,6 +1519,7 @@ "AggregatedListInstanceGroupsRequest", "AggregatedListInstancesRequest", "AggregatedListInstanceTemplatesRequest", + "AggregatedListInstantSnapshotsRequest", "AggregatedListInterconnectAttachmentsRequest", "AggregatedListMachineTypesRequest", "AggregatedListNetworkAttachmentsRequest", @@ -1644,6 +1669,7 @@ "DeleteInstancesInstanceGroupManagerRequest", "DeleteInstancesRegionInstanceGroupManagerRequest", "DeleteInstanceTemplateRequest", + "DeleteInstantSnapshotRequest", "DeleteInterconnectAttachmentRequest", "DeleteInterconnectRequest", "DeleteLicenseRequest", @@ -1668,6 +1694,7 @@ "DeleteRegionHealthCheckServiceRequest", "DeleteRegionInstanceGroupManagerRequest", "DeleteRegionInstanceTemplateRequest", + "DeleteRegionInstantSnapshotRequest", "DeleteRegionNetworkEndpointGroupRequest", "DeleteRegionNetworkFirewallPolicyRequest", "DeleteRegionNotificationEndpointRequest", @@ -1807,6 +1834,7 @@ "GetIamPolicyImageRequest", "GetIamPolicyInstanceRequest", "GetIamPolicyInstanceTemplateRequest", + "GetIamPolicyInstantSnapshotRequest", "GetIamPolicyLicenseRequest", "GetIamPolicyMachineImageRequest", "GetIamPolicyNetworkAttachmentRequest", @@ -1815,6 +1843,7 @@ "GetIamPolicyNodeTemplateRequest", "GetIamPolicyRegionBackendServiceRequest", "GetIamPolicyRegionDiskRequest", + "GetIamPolicyRegionInstantSnapshotRequest", "GetIamPolicyRegionNetworkFirewallPolicyRequest", "GetIamPolicyReservationRequest", "GetIamPolicyResourcePolicyRequest", @@ -1827,6 +1856,7 @@ "GetInstanceGroupRequest", "GetInstanceRequest", "GetInstanceTemplateRequest", + "GetInstantSnapshotRequest", "GetInterconnectAttachmentRequest", "GetInterconnectLocationRequest", "GetInterconnectRemoteLocationRequest", @@ -1860,6 +1890,7 @@ "GetRegionInstanceGroupManagerRequest", "GetRegionInstanceGroupRequest", "GetRegionInstanceTemplateRequest", + "GetRegionInstantSnapshotRequest", "GetRegionNetworkEndpointGroupRequest", "GetRegionNetworkFirewallPolicyRequest", "GetRegionNotificationEndpointRequest", @@ -1971,6 +2002,7 @@ "InsertInstanceGroupRequest", "InsertInstanceRequest", "InsertInstanceTemplateRequest", + "InsertInstantSnapshotRequest", "InsertInterconnectAttachmentRequest", "InsertInterconnectRequest", "InsertLicenseRequest", @@ -1993,6 +2025,7 @@ "InsertRegionHealthCheckServiceRequest", "InsertRegionInstanceGroupManagerRequest", "InsertRegionInstanceTemplateRequest", + "InsertRegionInstantSnapshotRequest", "InsertRegionNetworkEndpointGroupRequest", "InsertRegionNetworkFirewallPolicyRequest", "InsertRegionNotificationEndpointRequest", @@ -2094,6 +2127,11 @@ "InstanceTemplateList", "InstanceTemplatesScopedList", "InstanceWithNamedPorts", + "InstantSnapshot", + "InstantSnapshotAggregatedList", + "InstantSnapshotList", + "InstantSnapshotResourceStatus", + "InstantSnapshotsScopedList", "Int64RangeMatch", "Interconnect", "InterconnectAttachment", @@ -2165,6 +2203,7 @@ "ListInstancesRegionInstanceGroupsRequest", "ListInstancesRequest", "ListInstanceTemplatesRequest", + "ListInstantSnapshotsRequest", "ListInterconnectAttachmentsRequest", "ListInterconnectLocationsRequest", "ListInterconnectRemoteLocationsRequest", @@ -2203,6 +2242,7 @@ "ListRegionInstanceGroupManagersRequest", "ListRegionInstanceGroupsRequest", "ListRegionInstanceTemplatesRequest", + "ListRegionInstantSnapshotsRequest", "ListRegionNetworkEndpointGroupsRequest", "ListRegionNetworkFirewallPoliciesRequest", "ListRegionNotificationEndpointsRequest", @@ -2413,6 +2453,7 @@ "ProjectsEnableXpnResourceRequest", "ProjectsGetXpnResources", "ProjectsListXpnHostsRequest", + "ProjectsSetCloudArmorTierRequest", "ProjectsSetDefaultNetworkTierRequest", "PublicAdvertisedPrefix", "PublicAdvertisedPrefixList", @@ -2594,6 +2635,7 @@ "SetBackupTargetPoolRequest", "SetCertificateMapTargetHttpsProxyRequest", "SetCertificateMapTargetSslProxyRequest", + "SetCloudArmorTierProjectRequest", "SetCommonInstanceMetadataOperationMetadata", "SetCommonInstanceMetadataOperationMetadataPerLocationOperationInfo", "SetCommonInstanceMetadataProjectRequest", @@ -2609,6 +2651,7 @@ "SetIamPolicyImageRequest", "SetIamPolicyInstanceRequest", "SetIamPolicyInstanceTemplateRequest", + "SetIamPolicyInstantSnapshotRequest", "SetIamPolicyLicenseRequest", "SetIamPolicyMachineImageRequest", "SetIamPolicyNetworkAttachmentRequest", @@ -2617,6 +2660,7 @@ "SetIamPolicyNodeTemplateRequest", "SetIamPolicyRegionBackendServiceRequest", "SetIamPolicyRegionDiskRequest", + "SetIamPolicyRegionInstantSnapshotRequest", "SetIamPolicyRegionNetworkFirewallPolicyRequest", "SetIamPolicyReservationRequest", "SetIamPolicyResourcePolicyRequest", @@ -2633,9 +2677,11 @@ "SetLabelsGlobalForwardingRuleRequest", "SetLabelsImageRequest", "SetLabelsInstanceRequest", + "SetLabelsInstantSnapshotRequest", "SetLabelsInterconnectAttachmentRequest", "SetLabelsInterconnectRequest", "SetLabelsRegionDiskRequest", + "SetLabelsRegionInstantSnapshotRequest", "SetLabelsSecurityPolicyRequest", "SetLabelsSnapshotRequest", "SetLabelsTargetVpnGatewayRequest", @@ -2785,6 +2831,7 @@ "TestIamPermissionsImageRequest", "TestIamPermissionsInstanceRequest", "TestIamPermissionsInstanceTemplateRequest", + "TestIamPermissionsInstantSnapshotRequest", "TestIamPermissionsLicenseCodeRequest", "TestIamPermissionsLicenseRequest", "TestIamPermissionsMachineImageRequest", @@ -2796,6 +2843,7 @@ "TestIamPermissionsPacketMirroringRequest", "TestIamPermissionsRegionBackendServiceRequest", "TestIamPermissionsRegionDiskRequest", + "TestIamPermissionsRegionInstantSnapshotRequest", "TestIamPermissionsRegionNetworkFirewallPolicyRequest", "TestIamPermissionsReservationRequest", "TestIamPermissionsResourcePolicyRequest", diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py b/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py index 0ffe9bf52bab..9628f25f7a45 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py @@ -70,6 +70,7 @@ "AggregatedListInstanceGroupsRequest", "AggregatedListInstanceTemplatesRequest", "AggregatedListInstancesRequest", + "AggregatedListInstantSnapshotsRequest", "AggregatedListInterconnectAttachmentsRequest", "AggregatedListMachineTypesRequest", "AggregatedListNetworkAttachmentsRequest", @@ -218,6 +219,7 @@ "DeleteInstanceTemplateRequest", "DeleteInstancesInstanceGroupManagerRequest", "DeleteInstancesRegionInstanceGroupManagerRequest", + "DeleteInstantSnapshotRequest", "DeleteInterconnectAttachmentRequest", "DeleteInterconnectRequest", "DeleteLicenseRequest", @@ -242,6 +244,7 @@ "DeleteRegionHealthCheckServiceRequest", "DeleteRegionInstanceGroupManagerRequest", "DeleteRegionInstanceTemplateRequest", + "DeleteRegionInstantSnapshotRequest", "DeleteRegionNetworkEndpointGroupRequest", "DeleteRegionNetworkFirewallPolicyRequest", "DeleteRegionNotificationEndpointRequest", @@ -382,6 +385,7 @@ "GetIamPolicyImageRequest", "GetIamPolicyInstanceRequest", "GetIamPolicyInstanceTemplateRequest", + "GetIamPolicyInstantSnapshotRequest", "GetIamPolicyLicenseRequest", "GetIamPolicyMachineImageRequest", "GetIamPolicyNetworkAttachmentRequest", @@ -390,6 +394,7 @@ "GetIamPolicyNodeTemplateRequest", "GetIamPolicyRegionBackendServiceRequest", "GetIamPolicyRegionDiskRequest", + "GetIamPolicyRegionInstantSnapshotRequest", "GetIamPolicyRegionNetworkFirewallPolicyRequest", "GetIamPolicyReservationRequest", "GetIamPolicyResourcePolicyRequest", @@ -402,6 +407,7 @@ "GetInstanceGroupRequest", "GetInstanceRequest", "GetInstanceTemplateRequest", + "GetInstantSnapshotRequest", "GetInterconnectAttachmentRequest", "GetInterconnectLocationRequest", "GetInterconnectRemoteLocationRequest", @@ -435,6 +441,7 @@ "GetRegionInstanceGroupManagerRequest", "GetRegionInstanceGroupRequest", "GetRegionInstanceTemplateRequest", + "GetRegionInstantSnapshotRequest", "GetRegionNetworkEndpointGroupRequest", "GetRegionNetworkFirewallPolicyRequest", "GetRegionNotificationEndpointRequest", @@ -545,6 +552,7 @@ "InsertInstanceGroupRequest", "InsertInstanceRequest", "InsertInstanceTemplateRequest", + "InsertInstantSnapshotRequest", "InsertInterconnectAttachmentRequest", "InsertInterconnectRequest", "InsertLicenseRequest", @@ -567,6 +575,7 @@ "InsertRegionHealthCheckServiceRequest", "InsertRegionInstanceGroupManagerRequest", "InsertRegionInstanceTemplateRequest", + "InsertRegionInstantSnapshotRequest", "InsertRegionNetworkEndpointGroupRequest", "InsertRegionNetworkFirewallPolicyRequest", "InsertRegionNotificationEndpointRequest", @@ -668,6 +677,11 @@ "InstancesSetSecurityPolicyRequest", "InstancesSetServiceAccountRequest", "InstancesStartWithEncryptionKeyRequest", + "InstantSnapshot", + "InstantSnapshotAggregatedList", + "InstantSnapshotList", + "InstantSnapshotResourceStatus", + "InstantSnapshotsScopedList", "Int64RangeMatch", "Interconnect", "InterconnectAttachment", @@ -739,6 +753,7 @@ "ListInstancesInstanceGroupsRequest", "ListInstancesRegionInstanceGroupsRequest", "ListInstancesRequest", + "ListInstantSnapshotsRequest", "ListInterconnectAttachmentsRequest", "ListInterconnectLocationsRequest", "ListInterconnectRemoteLocationsRequest", @@ -777,6 +792,7 @@ "ListRegionInstanceGroupManagersRequest", "ListRegionInstanceGroupsRequest", "ListRegionInstanceTemplatesRequest", + "ListRegionInstantSnapshotsRequest", "ListRegionNetworkEndpointGroupsRequest", "ListRegionNetworkFirewallPoliciesRequest", "ListRegionNotificationEndpointsRequest", @@ -987,6 +1003,7 @@ "ProjectsEnableXpnResourceRequest", "ProjectsGetXpnResources", "ProjectsListXpnHostsRequest", + "ProjectsSetCloudArmorTierRequest", "ProjectsSetDefaultNetworkTierRequest", "PublicAdvertisedPrefix", "PublicAdvertisedPrefixList", @@ -1169,6 +1186,7 @@ "SetBackupTargetPoolRequest", "SetCertificateMapTargetHttpsProxyRequest", "SetCertificateMapTargetSslProxyRequest", + "SetCloudArmorTierProjectRequest", "SetCommonInstanceMetadataOperationMetadata", "SetCommonInstanceMetadataOperationMetadataPerLocationOperationInfo", "SetCommonInstanceMetadataProjectRequest", @@ -1184,6 +1202,7 @@ "SetIamPolicyImageRequest", "SetIamPolicyInstanceRequest", "SetIamPolicyInstanceTemplateRequest", + "SetIamPolicyInstantSnapshotRequest", "SetIamPolicyLicenseRequest", "SetIamPolicyMachineImageRequest", "SetIamPolicyNetworkAttachmentRequest", @@ -1192,6 +1211,7 @@ "SetIamPolicyNodeTemplateRequest", "SetIamPolicyRegionBackendServiceRequest", "SetIamPolicyRegionDiskRequest", + "SetIamPolicyRegionInstantSnapshotRequest", "SetIamPolicyRegionNetworkFirewallPolicyRequest", "SetIamPolicyReservationRequest", "SetIamPolicyResourcePolicyRequest", @@ -1208,9 +1228,11 @@ "SetLabelsGlobalForwardingRuleRequest", "SetLabelsImageRequest", "SetLabelsInstanceRequest", + "SetLabelsInstantSnapshotRequest", "SetLabelsInterconnectAttachmentRequest", "SetLabelsInterconnectRequest", "SetLabelsRegionDiskRequest", + "SetLabelsRegionInstantSnapshotRequest", "SetLabelsSecurityPolicyRequest", "SetLabelsSnapshotRequest", "SetLabelsTargetVpnGatewayRequest", @@ -1359,6 +1381,7 @@ "TestIamPermissionsImageRequest", "TestIamPermissionsInstanceRequest", "TestIamPermissionsInstanceTemplateRequest", + "TestIamPermissionsInstantSnapshotRequest", "TestIamPermissionsLicenseCodeRequest", "TestIamPermissionsLicenseRequest", "TestIamPermissionsMachineImageRequest", @@ -1370,6 +1393,7 @@ "TestIamPermissionsPacketMirroringRequest", "TestIamPermissionsRegionBackendServiceRequest", "TestIamPermissionsRegionDiskRequest", + "TestIamPermissionsRegionInstantSnapshotRequest", "TestIamPermissionsRegionNetworkFirewallPolicyRequest", "TestIamPermissionsReservationRequest", "TestIamPermissionsResourcePolicyRequest", @@ -4162,7 +4186,11 @@ class AggregatedListAcceleratorTypesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -4312,7 +4340,11 @@ class AggregatedListAddressesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -4462,7 +4494,11 @@ class AggregatedListAutoscalersRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -4612,7 +4648,11 @@ class AggregatedListBackendServicesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -4762,7 +4802,11 @@ class AggregatedListDiskTypesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -4912,7 +4956,11 @@ class AggregatedListDisksRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -5062,7 +5110,11 @@ class AggregatedListForwardingRulesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -5212,7 +5264,11 @@ class AggregatedListGlobalOperationsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -5362,7 +5418,11 @@ class AggregatedListHealthChecksRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -5512,7 +5572,11 @@ class AggregatedListInstanceGroupManagersRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -5662,7 +5726,11 @@ class AggregatedListInstanceGroupsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -5812,7 +5880,11 @@ class AggregatedListInstanceTemplatesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -5962,7 +6034,11 @@ class AggregatedListInstancesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -6014,9 +6090,9 @@ class AggregatedListInstancesRequest(proto.Message): ) -class AggregatedListInterconnectAttachmentsRequest(proto.Message): - r"""A request message for InterconnectAttachments.AggregatedList. - See the method description for details. +class AggregatedListInstantSnapshotsRequest(proto.Message): + r"""A request message for InstantSnapshots.AggregatedList. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -6112,7 +6188,11 @@ class AggregatedListInterconnectAttachmentsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -6164,9 +6244,9 @@ class AggregatedListInterconnectAttachmentsRequest(proto.Message): ) -class AggregatedListMachineTypesRequest(proto.Message): - r"""A request message for MachineTypes.AggregatedList. See the - method description for details. +class AggregatedListInterconnectAttachmentsRequest(proto.Message): + r"""A request message for InterconnectAttachments.AggregatedList. + See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -6262,7 +6342,11 @@ class AggregatedListMachineTypesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -6314,9 +6398,9 @@ class AggregatedListMachineTypesRequest(proto.Message): ) -class AggregatedListNetworkAttachmentsRequest(proto.Message): - r"""A request message for NetworkAttachments.AggregatedList. See - the method description for details. +class AggregatedListMachineTypesRequest(proto.Message): + r"""A request message for MachineTypes.AggregatedList. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -6412,7 +6496,11 @@ class AggregatedListNetworkAttachmentsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -6464,10 +6552,9 @@ class AggregatedListNetworkAttachmentsRequest(proto.Message): ) -class AggregatedListNetworkEdgeSecurityServicesRequest(proto.Message): - r"""A request message for - NetworkEdgeSecurityServices.AggregatedList. See the method - description for details. +class AggregatedListNetworkAttachmentsRequest(proto.Message): + r"""A request message for NetworkAttachments.AggregatedList. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -6559,11 +6646,15 @@ class AggregatedListNetworkEdgeSecurityServicesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Name of the project scoping this request. + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -6615,9 +6706,10 @@ class AggregatedListNetworkEdgeSecurityServicesRequest(proto.Message): ) -class AggregatedListNetworkEndpointGroupsRequest(proto.Message): - r"""A request message for NetworkEndpointGroups.AggregatedList. - See the method description for details. +class AggregatedListNetworkEdgeSecurityServicesRequest(proto.Message): + r"""A request message for + NetworkEdgeSecurityServices.AggregatedList. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -6709,11 +6801,15 @@ class AggregatedListNetworkEndpointGroupsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Project ID for this request. + Name of the project scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -6765,9 +6861,9 @@ class AggregatedListNetworkEndpointGroupsRequest(proto.Message): ) -class AggregatedListNodeGroupsRequest(proto.Message): - r"""A request message for NodeGroups.AggregatedList. See the - method description for details. +class AggregatedListNetworkEndpointGroupsRequest(proto.Message): + r"""A request message for NetworkEndpointGroups.AggregatedList. + See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -6863,7 +6959,11 @@ class AggregatedListNodeGroupsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -6915,8 +7015,8 @@ class AggregatedListNodeGroupsRequest(proto.Message): ) -class AggregatedListNodeTemplatesRequest(proto.Message): - r"""A request message for NodeTemplates.AggregatedList. See the +class AggregatedListNodeGroupsRequest(proto.Message): + r"""A request message for NodeGroups.AggregatedList. See the method description for details. @@ -7013,7 +7113,11 @@ class AggregatedListNodeTemplatesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -7065,8 +7169,8 @@ class AggregatedListNodeTemplatesRequest(proto.Message): ) -class AggregatedListNodeTypesRequest(proto.Message): - r"""A request message for NodeTypes.AggregatedList. See the +class AggregatedListNodeTemplatesRequest(proto.Message): + r"""A request message for NodeTemplates.AggregatedList. See the method description for details. @@ -7163,7 +7267,11 @@ class AggregatedListNodeTypesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -7215,9 +7323,9 @@ class AggregatedListNodeTypesRequest(proto.Message): ) -class AggregatedListPacketMirroringsRequest(proto.Message): - r"""A request message for PacketMirrorings.AggregatedList. See - the method description for details. +class AggregatedListNodeTypesRequest(proto.Message): + r"""A request message for NodeTypes.AggregatedList. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -7313,7 +7421,11 @@ class AggregatedListPacketMirroringsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -7365,158 +7477,8 @@ class AggregatedListPacketMirroringsRequest(proto.Message): ) -class AggregatedListPublicDelegatedPrefixesRequest(proto.Message): - r"""A request message for PublicDelegatedPrefixes.AggregatedList. - See the method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - filter (str): - A filter expression that filters resources listed in the - response. Most Compute resources support two types of filter - expressions: expressions that support regular expressions - and expressions that follow API improvement proposal - AIP-160. These two types of filter expressions cannot be - mixed in one request. If you want to use AIP-160, your - expression must specify the field name, an operator, and the - value that you want to use for filtering. The value must be - a string, a number, or a boolean. The operator must be - either ``=``, ``!=``, ``>``, ``<``, ``<=``, ``>=`` or ``:``. - For example, if you are filtering Compute Engine instances, - you can exclude instances named ``example-instance`` by - specifying ``name != example-instance``. The ``:*`` - comparison can be used to test whether a key has been - defined. For example, to find all objects with ``owner`` - label use: ``labels.owner:*`` You can also filter nested - fields. For example, you could specify - ``scheduling.automaticRestart = false`` to include instances - only if they are not scheduled for automatic restarts. You - can use filtering on nested fields to filter based on - resource labels. To filter on multiple expressions, provide - each separate expression within parentheses. For example: - ``(scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake")`` - By default, each expression is an ``AND`` expression. - However, you can include ``AND`` and ``OR`` expressions - explicitly. For example: - ``(cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true)`` - If you want to use a regular expression, use the ``eq`` - (equal) or ``ne`` (not equal) operator against a single - un-parenthesized expression with or without quotes or - against multiple parenthesized expressions. Examples: - ``fieldname eq unquoted literal`` - ``fieldname eq 'single quoted literal'`` - ``fieldname eq "double quoted literal"`` - ``(fieldname1 eq literal) (fieldname2 ne "literal")`` The - literal value is interpreted as a regular expression using - Google RE2 library syntax. The literal value must match the - entire field. For example, to filter for instances that do - not end with name "instance", you would use - ``name ne .*instance``. You cannot combine constraints on - multiple fields using regular expressions. - - This field is a member of `oneof`_ ``_filter``. - include_all_scopes (bool): - Indicates whether every visible scope for - each scope type (zone, region, global) should be - included in the response. For new resource types - added after this field, the flag has no effect - as new resource types will always include every - visible scope for each scope type in response. - For resource types which predate this field, if - this flag is omitted or false, only scopes of - the scope types where the resource type is - expected to be found will be included. - - This field is a member of `oneof`_ ``_include_all_scopes``. - max_results (int): - The maximum number of results per page that should be - returned. If the number of available results is larger than - ``maxResults``, Compute Engine returns a ``nextPageToken`` - that can be used to get the next page of results in - subsequent list requests. Acceptable values are ``0`` to - ``500``, inclusive. (Default: ``500``) - - This field is a member of `oneof`_ ``_max_results``. - order_by (str): - Sorts list results by a certain order. By default, results - are returned in alphanumerical order based on the resource - name. You can also sort results in descending order based on - the creation timestamp using - ``orderBy="creationTimestamp desc"``. This sorts results - based on the ``creationTimestamp`` field in reverse - chronological order (newest result first). Use this to sort - resources like operations so that the newest operation is - returned first. Currently, only sorting by ``name`` or - ``creationTimestamp desc`` is supported. - - This field is a member of `oneof`_ ``_order_by``. - page_token (str): - Specifies a page token to use. Set ``pageToken`` to the - ``nextPageToken`` returned by a previous list request to get - the next page of results. - - This field is a member of `oneof`_ ``_page_token``. - project (str): - Name of the project scoping this request. - return_partial_success (bool): - Opt-in for partial success behavior which - provides partial results in case of failure. The - default value is false. - - This field is a member of `oneof`_ ``_return_partial_success``. - service_project_number (int): - The Shared VPC service project id or service - project number for which aggregated list request - is invoked for subnetworks list-usable api. - - This field is a member of `oneof`_ ``_service_project_number``. - """ - - filter: str = proto.Field( - proto.STRING, - number=336120696, - optional=True, - ) - include_all_scopes: bool = proto.Field( - proto.BOOL, - number=391327988, - optional=True, - ) - max_results: int = proto.Field( - proto.UINT32, - number=54715419, - optional=True, - ) - order_by: str = proto.Field( - proto.STRING, - number=160562920, - optional=True, - ) - page_token: str = proto.Field( - proto.STRING, - number=19994697, - optional=True, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - return_partial_success: bool = proto.Field( - proto.BOOL, - number=517198390, - optional=True, - ) - service_project_number: int = proto.Field( - proto.INT64, - number=316757497, - optional=True, - ) - - -class AggregatedListRegionCommitmentsRequest(proto.Message): - r"""A request message for RegionCommitments.AggregatedList. See +class AggregatedListPacketMirroringsRequest(proto.Message): + r"""A request message for PacketMirrorings.AggregatedList. See the method description for details. @@ -7613,7 +7575,11 @@ class AggregatedListRegionCommitmentsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -7665,9 +7631,9 @@ class AggregatedListRegionCommitmentsRequest(proto.Message): ) -class AggregatedListReservationsRequest(proto.Message): - r"""A request message for Reservations.AggregatedList. See the - method description for details. +class AggregatedListPublicDelegatedPrefixesRequest(proto.Message): + r"""A request message for PublicDelegatedPrefixes.AggregatedList. + See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -7759,11 +7725,15 @@ class AggregatedListReservationsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Project ID for this request. + Name of the project scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -7815,8 +7785,8 @@ class AggregatedListReservationsRequest(proto.Message): ) -class AggregatedListResourcePoliciesRequest(proto.Message): - r"""A request message for ResourcePolicies.AggregatedList. See +class AggregatedListRegionCommitmentsRequest(proto.Message): + r"""A request message for RegionCommitments.AggregatedList. See the method description for details. @@ -7913,7 +7883,11 @@ class AggregatedListResourcePoliciesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -7965,9 +7939,9 @@ class AggregatedListResourcePoliciesRequest(proto.Message): ) -class AggregatedListRoutersRequest(proto.Message): - r"""A request message for Routers.AggregatedList. See the method - description for details. +class AggregatedListReservationsRequest(proto.Message): + r"""A request message for Reservations.AggregatedList. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -8063,7 +8037,11 @@ class AggregatedListRoutersRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -8115,8 +8093,8 @@ class AggregatedListRoutersRequest(proto.Message): ) -class AggregatedListSecurityPoliciesRequest(proto.Message): - r"""A request message for SecurityPolicies.AggregatedList. See +class AggregatedListResourcePoliciesRequest(proto.Message): + r"""A request message for ResourcePolicies.AggregatedList. See the method description for details. @@ -8209,11 +8187,15 @@ class AggregatedListSecurityPoliciesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Name of the project scoping this request. + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -8265,9 +8247,9 @@ class AggregatedListSecurityPoliciesRequest(proto.Message): ) -class AggregatedListServiceAttachmentsRequest(proto.Message): - r"""A request message for ServiceAttachments.AggregatedList. See - the method description for details. +class AggregatedListRoutersRequest(proto.Message): + r"""A request message for Routers.AggregatedList. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -8359,11 +8341,15 @@ class AggregatedListServiceAttachmentsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Name of the project scoping this request. + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -8415,9 +8401,9 @@ class AggregatedListServiceAttachmentsRequest(proto.Message): ) -class AggregatedListSslCertificatesRequest(proto.Message): - r"""A request message for SslCertificates.AggregatedList. See the - method description for details. +class AggregatedListSecurityPoliciesRequest(proto.Message): + r"""A request message for SecurityPolicies.AggregatedList. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -8513,7 +8499,11 @@ class AggregatedListSslCertificatesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -8565,9 +8555,9 @@ class AggregatedListSslCertificatesRequest(proto.Message): ) -class AggregatedListSslPoliciesRequest(proto.Message): - r"""A request message for SslPolicies.AggregatedList. See the - method description for details. +class AggregatedListServiceAttachmentsRequest(proto.Message): + r"""A request message for ServiceAttachments.AggregatedList. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -8663,7 +8653,11 @@ class AggregatedListSslPoliciesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -8715,8 +8709,8 @@ class AggregatedListSslPoliciesRequest(proto.Message): ) -class AggregatedListSubnetworksRequest(proto.Message): - r"""A request message for Subnetworks.AggregatedList. See the +class AggregatedListSslCertificatesRequest(proto.Message): + r"""A request message for SslCertificates.AggregatedList. See the method description for details. @@ -8809,11 +8803,323 @@ class AggregatedListSubnetworksRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Project ID for this request. + Name of the project scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + service_project_number (int): + The Shared VPC service project id or service + project number for which aggregated list request + is invoked for subnetworks list-usable api. + + This field is a member of `oneof`_ ``_service_project_number``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + include_all_scopes: bool = proto.Field( + proto.BOOL, + number=391327988, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + service_project_number: int = proto.Field( + proto.INT64, + number=316757497, + optional=True, + ) + + +class AggregatedListSslPoliciesRequest(proto.Message): + r"""A request message for SslPolicies.AggregatedList. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. Most Compute resources support two types of filter + expressions: expressions that support regular expressions + and expressions that follow API improvement proposal + AIP-160. These two types of filter expressions cannot be + mixed in one request. If you want to use AIP-160, your + expression must specify the field name, an operator, and the + value that you want to use for filtering. The value must be + a string, a number, or a boolean. The operator must be + either ``=``, ``!=``, ``>``, ``<``, ``<=``, ``>=`` or ``:``. + For example, if you are filtering Compute Engine instances, + you can exclude instances named ``example-instance`` by + specifying ``name != example-instance``. The ``:*`` + comparison can be used to test whether a key has been + defined. For example, to find all objects with ``owner`` + label use: ``labels.owner:*`` You can also filter nested + fields. For example, you could specify + ``scheduling.automaticRestart = false`` to include instances + only if they are not scheduled for automatic restarts. You + can use filtering on nested fields to filter based on + resource labels. To filter on multiple expressions, provide + each separate expression within parentheses. For example: + ``(scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake")`` + By default, each expression is an ``AND`` expression. + However, you can include ``AND`` and ``OR`` expressions + explicitly. For example: + ``(cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true)`` + If you want to use a regular expression, use the ``eq`` + (equal) or ``ne`` (not equal) operator against a single + un-parenthesized expression with or without quotes or + against multiple parenthesized expressions. Examples: + ``fieldname eq unquoted literal`` + ``fieldname eq 'single quoted literal'`` + ``fieldname eq "double quoted literal"`` + ``(fieldname1 eq literal) (fieldname2 ne "literal")`` The + literal value is interpreted as a regular expression using + Google RE2 library syntax. The literal value must match the + entire field. For example, to filter for instances that do + not end with name "instance", you would use + ``name ne .*instance``. You cannot combine constraints on + multiple fields using regular expressions. + + This field is a member of `oneof`_ ``_filter``. + include_all_scopes (bool): + Indicates whether every visible scope for + each scope type (zone, region, global) should be + included in the response. For new resource types + added after this field, the flag has no effect + as new resource types will always include every + visible scope for each scope type in response. + For resource types which predate this field, if + this flag is omitted or false, only scopes of + the scope types where the resource type is + expected to be found will be included. + + This field is a member of `oneof`_ ``_include_all_scopes``. + max_results (int): + The maximum number of results per page that should be + returned. If the number of available results is larger than + ``maxResults``, Compute Engine returns a ``nextPageToken`` + that can be used to get the next page of results in + subsequent list requests. Acceptable values are ``0`` to + ``500``, inclusive. (Default: ``500``) + + This field is a member of `oneof`_ ``_max_results``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. You can also sort results in descending order based on + the creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Name of the project scoping this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + service_project_number (int): + The Shared VPC service project id or service + project number for which aggregated list request + is invoked for subnetworks list-usable api. + + This field is a member of `oneof`_ ``_service_project_number``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + include_all_scopes: bool = proto.Field( + proto.BOOL, + number=391327988, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + service_project_number: int = proto.Field( + proto.INT64, + number=316757497, + optional=True, + ) + + +class AggregatedListSubnetworksRequest(proto.Message): + r"""A request message for Subnetworks.AggregatedList. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. Most Compute resources support two types of filter + expressions: expressions that support regular expressions + and expressions that follow API improvement proposal + AIP-160. These two types of filter expressions cannot be + mixed in one request. If you want to use AIP-160, your + expression must specify the field name, an operator, and the + value that you want to use for filtering. The value must be + a string, a number, or a boolean. The operator must be + either ``=``, ``!=``, ``>``, ``<``, ``<=``, ``>=`` or ``:``. + For example, if you are filtering Compute Engine instances, + you can exclude instances named ``example-instance`` by + specifying ``name != example-instance``. The ``:*`` + comparison can be used to test whether a key has been + defined. For example, to find all objects with ``owner`` + label use: ``labels.owner:*`` You can also filter nested + fields. For example, you could specify + ``scheduling.automaticRestart = false`` to include instances + only if they are not scheduled for automatic restarts. You + can use filtering on nested fields to filter based on + resource labels. To filter on multiple expressions, provide + each separate expression within parentheses. For example: + ``(scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake")`` + By default, each expression is an ``AND`` expression. + However, you can include ``AND`` and ``OR`` expressions + explicitly. For example: + ``(cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true)`` + If you want to use a regular expression, use the ``eq`` + (equal) or ``ne`` (not equal) operator against a single + un-parenthesized expression with or without quotes or + against multiple parenthesized expressions. Examples: + ``fieldname eq unquoted literal`` + ``fieldname eq 'single quoted literal'`` + ``fieldname eq "double quoted literal"`` + ``(fieldname1 eq literal) (fieldname2 ne "literal")`` The + literal value is interpreted as a regular expression using + Google RE2 library syntax. The literal value must match the + entire field. For example, to filter for instances that do + not end with name "instance", you would use + ``name ne .*instance``. You cannot combine constraints on + multiple fields using regular expressions. + + This field is a member of `oneof`_ ``_filter``. + include_all_scopes (bool): + Indicates whether every visible scope for + each scope type (zone, region, global) should be + included in the response. For new resource types + added after this field, the flag has no effect + as new resource types will always include every + visible scope for each scope type in response. + For resource types which predate this field, if + this flag is omitted or false, only scopes of + the scope types where the resource type is + expected to be found will be included. + + This field is a member of `oneof`_ ``_include_all_scopes``. + max_results (int): + The maximum number of results per page that should be + returned. If the number of available results is larger than + ``maxResults``, Compute Engine returns a ``nextPageToken`` + that can be used to get the next page of results in + subsequent list requests. Acceptable values are ``0`` to + ``500``, inclusive. (Default: ``500``) + + This field is a member of `oneof`_ ``_max_results``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. You can also sort results in descending order based on + the creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Project ID for this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -8963,7 +9269,11 @@ class AggregatedListTargetHttpProxiesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -9113,7 +9423,11 @@ class AggregatedListTargetHttpsProxiesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -9263,7 +9577,11 @@ class AggregatedListTargetInstancesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -9413,7 +9731,11 @@ class AggregatedListTargetPoolsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -9563,7 +9885,11 @@ class AggregatedListTargetTcpProxiesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -9713,7 +10039,11 @@ class AggregatedListTargetVpnGatewaysRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -9863,7 +10193,11 @@ class AggregatedListUrlMapsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -10013,7 +10347,11 @@ class AggregatedListVpnGatewaysRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -10163,7 +10501,11 @@ class AggregatedListVpnTunnelsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. service_project_number (int): @@ -11545,7 +11887,7 @@ class AttachedDiskInitializeParams(proto.Message): Indicates how much throughput to provision for the disk. This sets the number of throughput mb per second that the disk can handle. Values - must be between 1 and 7,124. + must greater than or equal to 1. This field is a member of `oneof`_ ``_provisioned_throughput``. replica_zones (MutableSequence[str]): @@ -13177,6 +13519,21 @@ class Backend(proto.Message): For usage guidelines, see Utilization balancing mode. This field is a member of `oneof`_ ``_max_utilization``. + preference (str): + This field indicates whether this backend + should be fully utilized before sending traffic + to backends with default preference. The + possible values are: - PREFERRED: Backends with + this preference level will be filled up to their + capacity limits first, based on RTT. - DEFAULT: + If preferred backends don't have enough + capacity, backends in this layer would be used + and traffic would be assigned based on the load + balancing algorithm you use. This is the default + Check the Preference enum for the list of + possible values. + + This field is a member of `oneof`_ ``_preference``. """ class BalancingMode(proto.Enum): @@ -13209,6 +13566,33 @@ class BalancingMode(proto.Enum): RATE = 2508000 UTILIZATION = 157008386 + class Preference(proto.Enum): + r"""This field indicates whether this backend should be fully + utilized before sending traffic to backends with default + preference. The possible values are: - PREFERRED: Backends with + this preference level will be filled up to their capacity limits + first, based on RTT. - DEFAULT: If preferred backends don't have + enough capacity, backends in this layer would be used and + traffic would be assigned based on the load balancing algorithm + you use. This is the default + + Values: + UNDEFINED_PREFERENCE (0): + A value indicating that the enum field is not + set. + DEFAULT (115302945): + No preference. + PREFERENCE_UNSPECIFIED (496219571): + If preference is unspecified, we set it to + the DEFAULT value + PREFERRED (418847841): + Traffic will be sent to this backend first. + """ + UNDEFINED_PREFERENCE = 0 + DEFAULT = 115302945 + PREFERENCE_UNSPECIFIED = 496219571 + PREFERRED = 418847841 + balancing_mode: str = proto.Field( proto.STRING, number=430286217, @@ -13269,6 +13653,11 @@ class BalancingMode(proto.Enum): number=148192199, optional=True, ) + preference: str = proto.Field( + proto.STRING, + number=150781147, + optional=True, + ) class BackendBucket(proto.Message): @@ -14201,6 +14590,13 @@ class BackendService(proto.Message): URLs of networkservices.ServiceBinding resources. Can only be set if load balancing scheme is INTERNAL_SELF_MANAGED. If set, lists of backends and health checks must be both empty. + service_lb_policy (str): + URL to networkservices.ServiceLbPolicy resource. Can only be + set if load balancing scheme is EXTERNAL, EXTERNAL_MANAGED, + INTERNAL_MANAGED or INTERNAL_SELF_MANAGED and the scope is + global. + + This field is a member of `oneof`_ ``_service_lb_policy``. session_affinity (str): Type of session affinity to use. The default is NONE. Only NONE and HEADER_FIELD are supported when the backend service @@ -14688,6 +15084,11 @@ class SessionAffinity(proto.Enum): proto.STRING, number=133581016, ) + service_lb_policy: str = proto.Field( + proto.STRING, + number=94848785, + optional=True, + ) session_affinity: str = proto.Field( proto.STRING, number=463888561, @@ -19937,6 +20338,60 @@ class DeleteInstancesRegionInstanceGroupManagerRequest(proto.Message): ) +class DeleteInstantSnapshotRequest(proto.Message): + r"""A request message for InstantSnapshots.Delete. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instant_snapshot (str): + Name of the InstantSnapshot resource to + delete. + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + zone (str): + The name of the zone for this request. + """ + + instant_snapshot: str = proto.Field( + proto.STRING, + number=391638626, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + class DeleteInterconnectAttachmentRequest(proto.Message): r"""A request message for InterconnectAttachments.Delete. See the method description for details. @@ -21163,6 +21618,60 @@ class DeleteRegionInstanceTemplateRequest(proto.Message): ) +class DeleteRegionInstantSnapshotRequest(proto.Message): + r"""A request message for RegionInstantSnapshots.Delete. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instant_snapshot (str): + Name of the InstantSnapshot resource to + delete. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + """ + + instant_snapshot: str = proto.Field( + proto.STRING, + number=391638626, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + + class DeleteRegionNetworkEndpointGroupRequest(proto.Message): r"""A request message for RegionNetworkEndpointGroups.Delete. See the method description for details. @@ -23619,7 +24128,7 @@ class Disk(proto.Message): Indicates how much throughput to provision for the disk. This sets the number of throughput mb per second that the disk can handle. Values - must be between 1 and 7,124. + must be greater than or equal to 1. This field is a member of `oneof`_ ``_provisioned_throughput``. region (str): @@ -23735,6 +24244,27 @@ class Disk(proto.Message): identify the exact version of the image that was used. This field is a member of `oneof`_ ``_source_image_id``. + source_instant_snapshot (str): + The source instant snapshot used to create + this disk. You can provide this as a partial or + full URL to the resource. For example, the + following are valid values: - + https://www.googleapis.com/compute/v1/projects/project/zones/zone + /instantSnapshots/instantSnapshot - + projects/project/zones/zone/instantSnapshots/instantSnapshot + - zones/zone/instantSnapshots/instantSnapshot + + This field is a member of `oneof`_ ``_source_instant_snapshot``. + source_instant_snapshot_id (str): + [Output Only] The unique ID of the instant snapshot used to + create this disk. This value identifies the exact instant + snapshot that was used to create this persistent disk. For + example, if you created the persistent disk from an instant + snapshot that was later deleted and recreated under the same + name, the source instant snapshot ID would identify the + exact version of the instant snapshot that was used. + + This field is a member of `oneof`_ ``_source_instant_snapshot_id``. source_snapshot (str): The source snapshot used to create this disk. You can provide this as a partial or full URL to @@ -24047,6 +24577,16 @@ class Status(proto.Enum): number=55328291, optional=True, ) + source_instant_snapshot: str = proto.Field( + proto.STRING, + number=219202054, + optional=True, + ) + source_instant_snapshot_id: str = proto.Field( + proto.STRING, + number=287582708, + optional=True, + ) source_snapshot: str = proto.Field( proto.STRING, number=126061928, @@ -25972,6 +26512,18 @@ class ExternalVpnGatewayInterface(proto.Message): Engine. This field is a member of `oneof`_ ``_ip_address``. + ipv6_address (str): + IPv6 address of the interface in the external + VPN gateway. This IPv6 address can be either + from your on-premise gateway or another Cloud + provider's VPN gateway, it cannot be an IP + address from Google Compute Engine. Must specify + an IPv6 address (not IPV4-mapped) using any + format described in RFC 4291 (e.g. + 2001:db8:0:0:2d9:51:0:0). The output format is + RFC 5952 format (e.g. 2001:db8::2d9:51:0:0). + + This field is a member of `oneof`_ ``_ipv6_address``. """ id: int = proto.Field( @@ -25984,6 +26536,11 @@ class ExternalVpnGatewayInterface(proto.Message): number=406272220, optional=True, ) + ipv6_address: str = proto.Field( + proto.STRING, + number=341563804, + optional=True, + ) class ExternalVpnGatewayList(proto.Message): @@ -29446,6 +30003,45 @@ class GetIamPolicyInstanceTemplateRequest(proto.Message): ) +class GetIamPolicyInstantSnapshotRequest(proto.Message): + r"""A request message for InstantSnapshots.GetIamPolicy. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + project (str): + Project ID for this request. + resource (str): + Name or id of the resource for this request. + zone (str): + The name of the zone for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + class GetIamPolicyLicenseRequest(proto.Message): r"""A request message for Licenses.GetIamPolicy. See the method description for details. @@ -29740,6 +30336,45 @@ class GetIamPolicyRegionDiskRequest(proto.Message): ) +class GetIamPolicyRegionInstantSnapshotRequest(proto.Message): + r"""A request message for RegionInstantSnapshots.GetIamPolicy. + See the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + resource (str): + Name or id of the resource for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + class GetIamPolicyRegionNetworkFirewallPolicyRequest(proto.Message): r"""A request message for RegionNetworkFirewallPolicies.GetIamPolicy. See the method @@ -30121,6 +30756,34 @@ class GetInstanceTemplateRequest(proto.Message): ) +class GetInstantSnapshotRequest(proto.Message): + r"""A request message for InstantSnapshots.Get. See the method + description for details. + + Attributes: + instant_snapshot (str): + Name of the InstantSnapshot resource to + return. + project (str): + Project ID for this request. + zone (str): + The name of the zone for this request. + """ + + instant_snapshot: str = proto.Field( + proto.STRING, + number=391638626, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + class GetInterconnectAttachmentRequest(proto.Message): r"""A request message for InterconnectAttachments.Get. See the method description for details. @@ -30463,7 +31126,11 @@ class GetNatMappingInfoRoutersRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. router (str): @@ -31092,6 +31759,34 @@ class GetRegionInstanceTemplateRequest(proto.Message): ) +class GetRegionInstantSnapshotRequest(proto.Message): + r"""A request message for RegionInstantSnapshots.Get. See the + method description for details. + + Attributes: + instant_snapshot (str): + Name of the InstantSnapshot resource to + return. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + """ + + instant_snapshot: str = proto.Field( + proto.STRING, + number=391638626, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + + class GetRegionNetworkEndpointGroupRequest(proto.Message): r"""A request message for RegionNetworkEndpointGroups.Get. See the method description for details. @@ -32399,7 +33094,11 @@ class GetXpnResourcesProjectsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -37179,6 +37878,60 @@ class InsertInstanceTemplateRequest(proto.Message): ) +class InsertInstantSnapshotRequest(proto.Message): + r"""A request message for InstantSnapshots.Insert. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instant_snapshot_resource (google.cloud.compute_v1.types.InstantSnapshot): + The body resource for this request + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + zone (str): + Name of the zone for this request. + """ + + instant_snapshot_resource: "InstantSnapshot" = proto.Field( + proto.MESSAGE, + number=383915339, + message="InstantSnapshot", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + class InsertInterconnectAttachmentRequest(proto.Message): r"""A request message for InterconnectAttachments.Insert. See the method description for details. @@ -38375,22 +39128,20 @@ class InsertRegionInstanceTemplateRequest(proto.Message): ) -class InsertRegionNetworkEndpointGroupRequest(proto.Message): - r"""A request message for RegionNetworkEndpointGroups.Insert. See - the method description for details. +class InsertRegionInstantSnapshotRequest(proto.Message): + r"""A request message for RegionInstantSnapshots.Insert. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - network_endpoint_group_resource (google.cloud.compute_v1.types.NetworkEndpointGroup): + instant_snapshot_resource (google.cloud.compute_v1.types.InstantSnapshot): The body resource for this request project (str): Project ID for this request. region (str): - The name of the region where you want to - create the network endpoint group. It should - comply with RFC1035. + Name of the region for this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -38411,10 +39162,10 @@ class InsertRegionNetworkEndpointGroupRequest(proto.Message): This field is a member of `oneof`_ ``_request_id``. """ - network_endpoint_group_resource: "NetworkEndpointGroup" = proto.Field( + instant_snapshot_resource: "InstantSnapshot" = proto.Field( proto.MESSAGE, - number=525788839, - message="NetworkEndpointGroup", + number=383915339, + message="InstantSnapshot", ) project: str = proto.Field( proto.STRING, @@ -38431,20 +39182,22 @@ class InsertRegionNetworkEndpointGroupRequest(proto.Message): ) -class InsertRegionNetworkFirewallPolicyRequest(proto.Message): - r"""A request message for RegionNetworkFirewallPolicies.Insert. - See the method description for details. +class InsertRegionNetworkEndpointGroupRequest(proto.Message): + r"""A request message for RegionNetworkEndpointGroups.Insert. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - firewall_policy_resource (google.cloud.compute_v1.types.FirewallPolicy): + network_endpoint_group_resource (google.cloud.compute_v1.types.NetworkEndpointGroup): The body resource for this request project (str): Project ID for this request. region (str): - Name of the region scoping this request. + The name of the region where you want to + create the network endpoint group. It should + comply with RFC1035. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -38465,10 +39218,10 @@ class InsertRegionNetworkFirewallPolicyRequest(proto.Message): This field is a member of `oneof`_ ``_request_id``. """ - firewall_policy_resource: "FirewallPolicy" = proto.Field( + network_endpoint_group_resource: "NetworkEndpointGroup" = proto.Field( proto.MESSAGE, - number=495049532, - message="FirewallPolicy", + number=525788839, + message="NetworkEndpointGroup", ) project: str = proto.Field( proto.STRING, @@ -38485,15 +39238,15 @@ class InsertRegionNetworkFirewallPolicyRequest(proto.Message): ) -class InsertRegionNotificationEndpointRequest(proto.Message): - r"""A request message for RegionNotificationEndpoints.Insert. See - the method description for details. +class InsertRegionNetworkFirewallPolicyRequest(proto.Message): + r"""A request message for RegionNetworkFirewallPolicies.Insert. + See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - notification_endpoint_resource (google.cloud.compute_v1.types.NotificationEndpoint): + firewall_policy_resource (google.cloud.compute_v1.types.FirewallPolicy): The body resource for this request project (str): Project ID for this request. @@ -38519,10 +39272,10 @@ class InsertRegionNotificationEndpointRequest(proto.Message): This field is a member of `oneof`_ ``_request_id``. """ - notification_endpoint_resource: "NotificationEndpoint" = proto.Field( + firewall_policy_resource: "FirewallPolicy" = proto.Field( proto.MESSAGE, - number=338459940, - message="NotificationEndpoint", + number=495049532, + message="FirewallPolicy", ) project: str = proto.Field( proto.STRING, @@ -38539,77 +39292,16 @@ class InsertRegionNotificationEndpointRequest(proto.Message): ) -class InsertRegionSecurityPolicyRequest(proto.Message): - r"""A request message for RegionSecurityPolicies.Insert. See the - method description for details. +class InsertRegionNotificationEndpointRequest(proto.Message): + r"""A request message for RegionNotificationEndpoints.Insert. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - project (str): - Project ID for this request. - region (str): - Name of the region scoping this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. For example, consider a situation - where you make an initial request and the - request times out. If you make the request again - with the same request ID, the server can check - if original operation with the same request ID - was received, and if so, will ignore the second - request. This prevents clients from accidentally - creating duplicate commitments. The request ID - must be a valid UUID with the exception that - zero UUID is not supported ( - 00000000-0000-0000-0000-000000000000). - - This field is a member of `oneof`_ ``_request_id``. - security_policy_resource (google.cloud.compute_v1.types.SecurityPolicy): + notification_endpoint_resource (google.cloud.compute_v1.types.NotificationEndpoint): The body resource for this request - validate_only (bool): - If true, the request will not be committed. - - This field is a member of `oneof`_ ``_validate_only``. - """ - - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, - optional=True, - ) - security_policy_resource: "SecurityPolicy" = proto.Field( - proto.MESSAGE, - number=216159612, - message="SecurityPolicy", - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=242744629, - optional=True, - ) - - -class InsertRegionSslCertificateRequest(proto.Message): - r"""A request message for RegionSslCertificates.Insert. See the - method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: project (str): Project ID for this request. region (str): @@ -38632,64 +39324,13 @@ class InsertRegionSslCertificateRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - ssl_certificate_resource (google.cloud.compute_v1.types.SslCertificate): - The body resource for this request """ - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, - optional=True, - ) - ssl_certificate_resource: "SslCertificate" = proto.Field( + notification_endpoint_resource: "NotificationEndpoint" = proto.Field( proto.MESSAGE, - number=180709897, - message="SslCertificate", + number=338459940, + message="NotificationEndpoint", ) - - -class InsertRegionSslPolicyRequest(proto.Message): - r"""A request message for RegionSslPolicies.Insert. See the - method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - project (str): - Project ID for this request. - region (str): - Name of the region scoping this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. For example, consider a situation - where you make an initial request and the - request times out. If you make the request again - with the same request ID, the server can check - if original operation with the same request ID - was received, and if so, will ignore the second - request. This prevents clients from accidentally - creating duplicate commitments. The request ID - must be a valid UUID with the exception that - zero UUID is not supported ( - 00000000-0000-0000-0000-000000000000). - - This field is a member of `oneof`_ ``_request_id``. - ssl_policy_resource (google.cloud.compute_v1.types.SslPolicy): - The body resource for this request - """ - project: str = proto.Field( proto.STRING, number=227560217, @@ -38703,15 +39344,10 @@ class InsertRegionSslPolicyRequest(proto.Message): number=37109963, optional=True, ) - ssl_policy_resource: "SslPolicy" = proto.Field( - proto.MESSAGE, - number=274891848, - message="SslPolicy", - ) -class InsertRegionTargetHttpProxyRequest(proto.Message): - r"""A request message for RegionTargetHttpProxies.Insert. See the +class InsertRegionSecurityPolicyRequest(proto.Message): + r"""A request message for RegionSecurityPolicies.Insert. See the method description for details. @@ -38740,8 +39376,12 @@ class InsertRegionTargetHttpProxyRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - target_http_proxy_resource (google.cloud.compute_v1.types.TargetHttpProxy): + security_policy_resource (google.cloud.compute_v1.types.SecurityPolicy): The body resource for this request + validate_only (bool): + If true, the request will not be committed. + + This field is a member of `oneof`_ ``_validate_only``. """ project: str = proto.Field( @@ -38757,69 +39397,20 @@ class InsertRegionTargetHttpProxyRequest(proto.Message): number=37109963, optional=True, ) - target_http_proxy_resource: "TargetHttpProxy" = proto.Field( + security_policy_resource: "SecurityPolicy" = proto.Field( proto.MESSAGE, - number=24696744, - message="TargetHttpProxy", - ) - - -class InsertRegionTargetHttpsProxyRequest(proto.Message): - r"""A request message for RegionTargetHttpsProxies.Insert. See - the method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - project (str): - Project ID for this request. - region (str): - Name of the region scoping this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. For example, consider a situation - where you make an initial request and the - request times out. If you make the request again - with the same request ID, the server can check - if original operation with the same request ID - was received, and if so, will ignore the second - request. This prevents clients from accidentally - creating duplicate commitments. The request ID - must be a valid UUID with the exception that - zero UUID is not supported ( - 00000000-0000-0000-0000-000000000000). - - This field is a member of `oneof`_ ``_request_id``. - target_https_proxy_resource (google.cloud.compute_v1.types.TargetHttpsProxy): - The body resource for this request - """ - - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - region: str = proto.Field( - proto.STRING, - number=138946292, + number=216159612, + message="SecurityPolicy", ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, + validate_only: bool = proto.Field( + proto.BOOL, + number=242744629, optional=True, ) - target_https_proxy_resource: "TargetHttpsProxy" = proto.Field( - proto.MESSAGE, - number=433657473, - message="TargetHttpsProxy", - ) -class InsertRegionTargetTcpProxyRequest(proto.Message): - r"""A request message for RegionTargetTcpProxies.Insert. See the +class InsertRegionSslCertificateRequest(proto.Message): + r"""A request message for RegionSslCertificates.Insert. See the method description for details. @@ -38848,7 +39439,7 @@ class InsertRegionTargetTcpProxyRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - target_tcp_proxy_resource (google.cloud.compute_v1.types.TargetTcpProxy): + ssl_certificate_resource (google.cloud.compute_v1.types.SslCertificate): The body resource for this request """ @@ -38865,16 +39456,16 @@ class InsertRegionTargetTcpProxyRequest(proto.Message): number=37109963, optional=True, ) - target_tcp_proxy_resource: "TargetTcpProxy" = proto.Field( + ssl_certificate_resource: "SslCertificate" = proto.Field( proto.MESSAGE, - number=145913931, - message="TargetTcpProxy", + number=180709897, + message="SslCertificate", ) -class InsertRegionUrlMapRequest(proto.Message): - r"""A request message for RegionUrlMaps.Insert. See the method - description for details. +class InsertRegionSslPolicyRequest(proto.Message): + r"""A request message for RegionSslPolicies.Insert. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -38885,11 +39476,24 @@ class InsertRegionUrlMapRequest(proto.Message): region (str): Name of the region scoping this request. request_id (str): - begin_interface: MixerMutationRequestBuilder Request ID to - support idempotency. + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - url_map_resource (google.cloud.compute_v1.types.UrlMap): + ssl_policy_resource (google.cloud.compute_v1.types.SslPolicy): The body resource for this request """ @@ -38906,16 +39510,16 @@ class InsertRegionUrlMapRequest(proto.Message): number=37109963, optional=True, ) - url_map_resource: "UrlMap" = proto.Field( + ssl_policy_resource: "SslPolicy" = proto.Field( proto.MESSAGE, - number=168675425, - message="UrlMap", + number=274891848, + message="SslPolicy", ) -class InsertReservationRequest(proto.Message): - r"""A request message for Reservations.Insert. See the method - description for details. +class InsertRegionTargetHttpProxyRequest(proto.Message): + r"""A request message for RegionTargetHttpProxies.Insert. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -38923,6 +39527,8 @@ class InsertReservationRequest(proto.Message): Attributes: project (str): Project ID for this request. + region (str): + Name of the region scoping this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -38941,35 +39547,33 @@ class InsertReservationRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - reservation_resource (google.cloud.compute_v1.types.Reservation): + target_http_proxy_resource (google.cloud.compute_v1.types.TargetHttpProxy): The body resource for this request - zone (str): - Name of the zone for this request. """ project: str = proto.Field( proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) request_id: str = proto.Field( proto.STRING, number=37109963, optional=True, ) - reservation_resource: "Reservation" = proto.Field( + target_http_proxy_resource: "TargetHttpProxy" = proto.Field( proto.MESSAGE, - number=285030177, - message="Reservation", - ) - zone: str = proto.Field( - proto.STRING, - number=3744684, + number=24696744, + message="TargetHttpProxy", ) -class InsertResourcePolicyRequest(proto.Message): - r"""A request message for ResourcePolicies.Insert. See the method - description for details. +class InsertRegionTargetHttpsProxyRequest(proto.Message): + r"""A request message for RegionTargetHttpsProxies.Insert. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -38978,7 +39582,7 @@ class InsertResourcePolicyRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region for this request. + Name of the region scoping this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -38997,7 +39601,7 @@ class InsertResourcePolicyRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - resource_policy_resource (google.cloud.compute_v1.types.ResourcePolicy): + target_https_proxy_resource (google.cloud.compute_v1.types.TargetHttpsProxy): The body resource for this request """ @@ -39014,16 +39618,16 @@ class InsertResourcePolicyRequest(proto.Message): number=37109963, optional=True, ) - resource_policy_resource: "ResourcePolicy" = proto.Field( + target_https_proxy_resource: "TargetHttpsProxy" = proto.Field( proto.MESSAGE, - number=76826186, - message="ResourcePolicy", + number=433657473, + message="TargetHttpsProxy", ) -class InsertRouteRequest(proto.Message): - r"""A request message for Routes.Insert. See the method - description for details. +class InsertRegionTargetTcpProxyRequest(proto.Message): + r"""A request message for RegionTargetTcpProxies.Insert. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -39031,6 +39635,8 @@ class InsertRouteRequest(proto.Message): Attributes: project (str): Project ID for this request. + region (str): + Name of the region scoping this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -39049,7 +39655,7 @@ class InsertRouteRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - route_resource (google.cloud.compute_v1.types.Route): + target_tcp_proxy_resource (google.cloud.compute_v1.types.TargetTcpProxy): The body resource for this request """ @@ -39057,20 +39663,24 @@ class InsertRouteRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) request_id: str = proto.Field( proto.STRING, number=37109963, optional=True, ) - route_resource: "Route" = proto.Field( + target_tcp_proxy_resource: "TargetTcpProxy" = proto.Field( proto.MESSAGE, - number=225428804, - message="Route", + number=145913931, + message="TargetTcpProxy", ) -class InsertRouterRequest(proto.Message): - r"""A request message for Routers.Insert. See the method +class InsertRegionUrlMapRequest(proto.Message): + r"""A request message for RegionUrlMaps.Insert. See the method description for details. @@ -39080,26 +39690,13 @@ class InsertRouterRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region for this request. + Name of the region scoping this request. request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. For example, consider a situation - where you make an initial request and the - request times out. If you make the request again - with the same request ID, the server can check - if original operation with the same request ID - was received, and if so, will ignore the second - request. This prevents clients from accidentally - creating duplicate commitments. The request ID - must be a valid UUID with the exception that - zero UUID is not supported ( - 00000000-0000-0000-0000-000000000000). + begin_interface: MixerMutationRequestBuilder Request ID to + support idempotency. This field is a member of `oneof`_ ``_request_id``. - router_resource (google.cloud.compute_v1.types.Router): + url_map_resource (google.cloud.compute_v1.types.UrlMap): The body resource for this request """ @@ -39116,15 +39713,15 @@ class InsertRouterRequest(proto.Message): number=37109963, optional=True, ) - router_resource: "Router" = proto.Field( + url_map_resource: "UrlMap" = proto.Field( proto.MESSAGE, - number=155222084, - message="Router", + number=168675425, + message="UrlMap", ) -class InsertSecurityPolicyRequest(proto.Message): - r"""A request message for SecurityPolicies.Insert. See the method +class InsertReservationRequest(proto.Message): + r"""A request message for Reservations.Insert. See the method description for details. @@ -39151,12 +39748,10 @@ class InsertSecurityPolicyRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - security_policy_resource (google.cloud.compute_v1.types.SecurityPolicy): + reservation_resource (google.cloud.compute_v1.types.Reservation): The body resource for this request - validate_only (bool): - If true, the request will not be committed. - - This field is a member of `oneof`_ ``_validate_only``. + zone (str): + Name of the zone for this request. """ project: str = proto.Field( @@ -39168,21 +39763,20 @@ class InsertSecurityPolicyRequest(proto.Message): number=37109963, optional=True, ) - security_policy_resource: "SecurityPolicy" = proto.Field( + reservation_resource: "Reservation" = proto.Field( proto.MESSAGE, - number=216159612, - message="SecurityPolicy", + number=285030177, + message="Reservation", ) - validate_only: bool = proto.Field( - proto.BOOL, - number=242744629, - optional=True, + zone: str = proto.Field( + proto.STRING, + number=3744684, ) -class InsertServiceAttachmentRequest(proto.Message): - r"""A request message for ServiceAttachments.Insert. See the - method description for details. +class InsertResourcePolicyRequest(proto.Message): + r"""A request message for ResourcePolicies.Insert. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -39191,7 +39785,7 @@ class InsertServiceAttachmentRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region of this request. + Name of the region for this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -39210,7 +39804,7 @@ class InsertServiceAttachmentRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - service_attachment_resource (google.cloud.compute_v1.types.ServiceAttachment): + resource_policy_resource (google.cloud.compute_v1.types.ResourcePolicy): The body resource for this request """ @@ -39227,15 +39821,15 @@ class InsertServiceAttachmentRequest(proto.Message): number=37109963, optional=True, ) - service_attachment_resource: "ServiceAttachment" = proto.Field( + resource_policy_resource: "ResourcePolicy" = proto.Field( proto.MESSAGE, - number=472980256, - message="ServiceAttachment", + number=76826186, + message="ResourcePolicy", ) -class InsertSnapshotRequest(proto.Message): - r"""A request message for Snapshots.Insert. See the method +class InsertRouteRequest(proto.Message): + r"""A request message for Routes.Insert. See the method description for details. @@ -39262,7 +39856,7 @@ class InsertSnapshotRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - snapshot_resource (google.cloud.compute_v1.types.Snapshot): + route_resource (google.cloud.compute_v1.types.Route): The body resource for this request """ @@ -39275,15 +39869,15 @@ class InsertSnapshotRequest(proto.Message): number=37109963, optional=True, ) - snapshot_resource: "Snapshot" = proto.Field( + route_resource: "Route" = proto.Field( proto.MESSAGE, - number=481319977, - message="Snapshot", + number=225428804, + message="Route", ) -class InsertSslCertificateRequest(proto.Message): - r"""A request message for SslCertificates.Insert. See the method +class InsertRouterRequest(proto.Message): + r"""A request message for Routers.Insert. See the method description for details. @@ -39292,6 +39886,8 @@ class InsertSslCertificateRequest(proto.Message): Attributes: project (str): Project ID for this request. + region (str): + Name of the region for this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -39310,7 +39906,7 @@ class InsertSslCertificateRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - ssl_certificate_resource (google.cloud.compute_v1.types.SslCertificate): + router_resource (google.cloud.compute_v1.types.Router): The body resource for this request """ @@ -39318,20 +39914,24 @@ class InsertSslCertificateRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) request_id: str = proto.Field( proto.STRING, number=37109963, optional=True, ) - ssl_certificate_resource: "SslCertificate" = proto.Field( + router_resource: "Router" = proto.Field( proto.MESSAGE, - number=180709897, - message="SslCertificate", + number=155222084, + message="Router", ) -class InsertSslPolicyRequest(proto.Message): - r"""A request message for SslPolicies.Insert. See the method +class InsertSecurityPolicyRequest(proto.Message): + r"""A request message for SecurityPolicies.Insert. See the method description for details. @@ -39358,8 +39958,12 @@ class InsertSslPolicyRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - ssl_policy_resource (google.cloud.compute_v1.types.SslPolicy): + security_policy_resource (google.cloud.compute_v1.types.SecurityPolicy): The body resource for this request + validate_only (bool): + If true, the request will not be committed. + + This field is a member of `oneof`_ ``_validate_only``. """ project: str = proto.Field( @@ -39371,16 +39975,21 @@ class InsertSslPolicyRequest(proto.Message): number=37109963, optional=True, ) - ssl_policy_resource: "SslPolicy" = proto.Field( + security_policy_resource: "SecurityPolicy" = proto.Field( proto.MESSAGE, - number=274891848, - message="SslPolicy", + number=216159612, + message="SecurityPolicy", + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=242744629, + optional=True, ) -class InsertSubnetworkRequest(proto.Message): - r"""A request message for Subnetworks.Insert. See the method - description for details. +class InsertServiceAttachmentRequest(proto.Message): + r"""A request message for ServiceAttachments.Insert. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -39389,7 +39998,7 @@ class InsertSubnetworkRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + Name of the region of this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -39408,7 +40017,7 @@ class InsertSubnetworkRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - subnetwork_resource (google.cloud.compute_v1.types.Subnetwork): + service_attachment_resource (google.cloud.compute_v1.types.ServiceAttachment): The body resource for this request """ @@ -39425,16 +40034,16 @@ class InsertSubnetworkRequest(proto.Message): number=37109963, optional=True, ) - subnetwork_resource: "Subnetwork" = proto.Field( + service_attachment_resource: "ServiceAttachment" = proto.Field( proto.MESSAGE, - number=42233151, - message="Subnetwork", + number=472980256, + message="ServiceAttachment", ) -class InsertTargetGrpcProxyRequest(proto.Message): - r"""A request message for TargetGrpcProxies.Insert. See the - method description for details. +class InsertSnapshotRequest(proto.Message): + r"""A request message for Snapshots.Insert. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -39460,7 +40069,7 @@ class InsertTargetGrpcProxyRequest(proto.Message): 00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - target_grpc_proxy_resource (google.cloud.compute_v1.types.TargetGrpcProxy): + snapshot_resource (google.cloud.compute_v1.types.Snapshot): The body resource for this request """ @@ -39473,16 +40082,214 @@ class InsertTargetGrpcProxyRequest(proto.Message): number=37109963, optional=True, ) - target_grpc_proxy_resource: "TargetGrpcProxy" = proto.Field( + snapshot_resource: "Snapshot" = proto.Field( proto.MESSAGE, - number=328922450, - message="TargetGrpcProxy", + number=481319977, + message="Snapshot", ) -class InsertTargetHttpProxyRequest(proto.Message): - r"""A request message for TargetHttpProxies.Insert. See the - method description for details. +class InsertSslCertificateRequest(proto.Message): + r"""A request message for SslCertificates.Insert. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + ssl_certificate_resource (google.cloud.compute_v1.types.SslCertificate): + The body resource for this request + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + ssl_certificate_resource: "SslCertificate" = proto.Field( + proto.MESSAGE, + number=180709897, + message="SslCertificate", + ) + + +class InsertSslPolicyRequest(proto.Message): + r"""A request message for SslPolicies.Insert. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + ssl_policy_resource (google.cloud.compute_v1.types.SslPolicy): + The body resource for this request + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + ssl_policy_resource: "SslPolicy" = proto.Field( + proto.MESSAGE, + number=274891848, + message="SslPolicy", + ) + + +class InsertSubnetworkRequest(proto.Message): + r"""A request message for Subnetworks.Insert. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Project ID for this request. + region (str): + Name of the region scoping this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + subnetwork_resource (google.cloud.compute_v1.types.Subnetwork): + The body resource for this request + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + subnetwork_resource: "Subnetwork" = proto.Field( + proto.MESSAGE, + number=42233151, + message="Subnetwork", + ) + + +class InsertTargetGrpcProxyRequest(proto.Message): + r"""A request message for TargetGrpcProxies.Insert. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + target_grpc_proxy_resource (google.cloud.compute_v1.types.TargetGrpcProxy): + The body resource for this request + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + target_grpc_proxy_resource: "TargetGrpcProxy" = proto.Field( + proto.MESSAGE, + number=328922450, + message="TargetGrpcProxy", + ) + + +class InsertTargetHttpProxyRequest(proto.Message): + r"""A request message for TargetHttpProxies.Insert. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -41759,6 +42566,17 @@ class InstanceGroupManagerInstanceLifecyclePolicy(proto.Message): .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + default_action_on_failure (str): + The action that a MIG performs on a failed or an unhealthy + VM. A VM is marked as unhealthy when the application running + on that VM fails a health check. Valid values are - REPAIR + (default): MIG automatically repairs a failed or an + unhealthy VM by recreating it. For more information, see + About repairing VMs in a MIG. - DO_NOTHING: MIG does not + repair a failed or an unhealthy VM. Check the + DefaultActionOnFailure enum for the list of possible values. + + This field is a member of `oneof`_ ``_default_action_on_failure``. force_update_on_repair (str): A bit indicating whether to forcefully apply the group's latest configuration when repairing @@ -41775,6 +42593,30 @@ class InstanceGroupManagerInstanceLifecyclePolicy(proto.Message): This field is a member of `oneof`_ ``_force_update_on_repair``. """ + class DefaultActionOnFailure(proto.Enum): + r"""The action that a MIG performs on a failed or an unhealthy VM. A VM + is marked as unhealthy when the application running on that VM fails + a health check. Valid values are - REPAIR (default): MIG + automatically repairs a failed or an unhealthy VM by recreating it. + For more information, see About repairing VMs in a MIG. - + DO_NOTHING: MIG does not repair a failed or an unhealthy VM. + + Values: + UNDEFINED_DEFAULT_ACTION_ON_FAILURE (0): + A value indicating that the enum field is not + set. + DO_NOTHING (451307513): + MIG does not repair a failed or an unhealthy + VM. + REPAIR (266277773): + (Default) MIG automatically repairs a failed + or an unhealthy VM by recreating it. For more + information, see About repairing VMs in a MIG. + """ + UNDEFINED_DEFAULT_ACTION_ON_FAILURE = 0 + DO_NOTHING = 451307513 + REPAIR = 266277773 + class ForceUpdateOnRepair(proto.Enum): r"""A bit indicating whether to forcefully apply the group's latest configuration when repairing a VM. Valid options are: - @@ -41797,6 +42639,11 @@ class ForceUpdateOnRepair(proto.Enum): NO = 2497 YES = 87751 + default_action_on_failure: str = proto.Field( + proto.STRING, + number=61383253, + optional=True, + ) force_update_on_repair: str = proto.Field( proto.STRING, number=356302027, @@ -44589,6 +45436,489 @@ class InstancesStartWithEncryptionKeyRequest(proto.Message): ) +class InstantSnapshot(proto.Message): + r"""Represents a InstantSnapshot resource. You can use instant + snapshots to create disk rollback points quickly.. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + architecture (str): + [Output Only] The architecture of the instant snapshot. + Valid values are ARM64 or X86_64. Check the Architecture + enum for the list of possible values. + + This field is a member of `oneof`_ ``_architecture``. + creation_timestamp (str): + [Output Only] Creation timestamp in RFC3339 text format. + + This field is a member of `oneof`_ ``_creation_timestamp``. + description (str): + An optional description of this resource. + Provide this property when you create the + resource. + + This field is a member of `oneof`_ ``_description``. + disk_size_gb (int): + [Output Only] Size of the source disk, specified in GB. + + This field is a member of `oneof`_ ``_disk_size_gb``. + id (int): + [Output Only] The unique identifier for the resource. This + identifier is defined by the server. + + This field is a member of `oneof`_ ``_id``. + kind (str): + [Output Only] Type of the resource. Always + compute#instantSnapshot for InstantSnapshot resources. + + This field is a member of `oneof`_ ``_kind``. + label_fingerprint (str): + A fingerprint for the labels being applied to + this InstantSnapshot, which is essentially a + hash of the labels set used for optimistic + locking. The fingerprint is initially generated + by Compute Engine and changes after every + request to modify or update labels. You must + always provide an up-to-date fingerprint hash in + order to update or change labels, otherwise the + request will fail with error 412 + conditionNotMet. To see the latest fingerprint, + make a get() request to retrieve a + InstantSnapshot. + + This field is a member of `oneof`_ ``_label_fingerprint``. + labels (MutableMapping[str, str]): + Labels to apply to this InstantSnapshot. + These can be later modified by the setLabels + method. Label values may be empty. + name (str): + Name of the resource; provided by the client when the + resource is created. The name must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be 1-63 + characters long and match the regular expression + ``[a-z]([-a-z0-9]*[a-z0-9])?`` which means the first + character must be a lowercase letter, and all following + characters must be a dash, lowercase letter, or digit, + except the last character, which cannot be a dash. + + This field is a member of `oneof`_ ``_name``. + region (str): + [Output Only] URL of the region where the instant snapshot + resides. You must specify this field as part of the HTTP + request URL. It is not settable as a field in the request + body. + + This field is a member of `oneof`_ ``_region``. + resource_status (google.cloud.compute_v1.types.InstantSnapshotResourceStatus): + [Output Only] Status information for the instant snapshot + resource. + + This field is a member of `oneof`_ ``_resource_status``. + satisfies_pzi (bool): + Output only. Reserved for future use. + + This field is a member of `oneof`_ ``_satisfies_pzi``. + satisfies_pzs (bool): + [Output Only] Reserved for future use. + + This field is a member of `oneof`_ ``_satisfies_pzs``. + self_link (str): + [Output Only] Server-defined URL for the resource. + + This field is a member of `oneof`_ ``_self_link``. + self_link_with_id (str): + [Output Only] Server-defined URL for this resource's + resource id. + + This field is a member of `oneof`_ ``_self_link_with_id``. + source_disk (str): + URL of the source disk used to create this + instant snapshot. Note that the source disk must + be in the same zone/region as the instant + snapshot to be created. This can be a full or + valid partial URL. For example, the following + are valid values: - + https://www.googleapis.com/compute/v1/projects/project/zones/zone + /disks/disk - + https://www.googleapis.com/compute/v1/projects/project/regions/region + /disks/disk - + projects/project/zones/zone/disks/disk - + projects/project/regions/region/disks/disk - + zones/zone/disks/disk - + regions/region/disks/disk + + This field is a member of `oneof`_ ``_source_disk``. + source_disk_id (str): + [Output Only] The ID value of the disk used to create this + InstantSnapshot. This value may be used to determine whether + the InstantSnapshot was taken from the current or a previous + instance of a given disk name. + + This field is a member of `oneof`_ ``_source_disk_id``. + status (str): + [Output Only] The status of the instantSnapshot. This can be + CREATING, DELETING, FAILED, or READY. Check the Status enum + for the list of possible values. + + This field is a member of `oneof`_ ``_status``. + zone (str): + [Output Only] URL of the zone where the instant snapshot + resides. You must specify this field as part of the HTTP + request URL. It is not settable as a field in the request + body. + + This field is a member of `oneof`_ ``_zone``. + """ + + class Architecture(proto.Enum): + r"""[Output Only] The architecture of the instant snapshot. Valid values + are ARM64 or X86_64. + + Values: + UNDEFINED_ARCHITECTURE (0): + A value indicating that the enum field is not + set. + ARCHITECTURE_UNSPECIFIED (394750507): + Default value indicating Architecture is not + set. + ARM64 (62547450): + Machines with architecture ARM64 + X86_64 (425300551): + Machines with architecture X86_64 + """ + UNDEFINED_ARCHITECTURE = 0 + ARCHITECTURE_UNSPECIFIED = 394750507 + ARM64 = 62547450 + X86_64 = 425300551 + + class Status(proto.Enum): + r"""[Output Only] The status of the instantSnapshot. This can be + CREATING, DELETING, FAILED, or READY. + + Values: + UNDEFINED_STATUS (0): + A value indicating that the enum field is not + set. + CREATING (455564985): + InstantSnapshot creation is in progress. + DELETING (528602024): + InstantSnapshot is currently being deleted. + FAILED (455706685): + InstantSnapshot creation failed. + READY (77848963): + InstantSnapshot has been created + successfully. + """ + UNDEFINED_STATUS = 0 + CREATING = 455564985 + DELETING = 528602024 + FAILED = 455706685 + READY = 77848963 + + architecture: str = proto.Field( + proto.STRING, + number=302803283, + optional=True, + ) + creation_timestamp: str = proto.Field( + proto.STRING, + number=30525366, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=422937596, + optional=True, + ) + disk_size_gb: int = proto.Field( + proto.INT64, + number=316263735, + optional=True, + ) + id: int = proto.Field( + proto.UINT64, + number=3355, + optional=True, + ) + kind: str = proto.Field( + proto.STRING, + number=3292052, + optional=True, + ) + label_fingerprint: str = proto.Field( + proto.STRING, + number=178124825, + optional=True, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=500195327, + ) + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + optional=True, + ) + resource_status: "InstantSnapshotResourceStatus" = proto.Field( + proto.MESSAGE, + number=249429315, + optional=True, + message="InstantSnapshotResourceStatus", + ) + satisfies_pzi: bool = proto.Field( + proto.BOOL, + number=480964257, + optional=True, + ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=480964267, + optional=True, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + self_link_with_id: str = proto.Field( + proto.STRING, + number=44520962, + optional=True, + ) + source_disk: str = proto.Field( + proto.STRING, + number=451753793, + optional=True, + ) + source_disk_id: str = proto.Field( + proto.STRING, + number=454190809, + optional=True, + ) + status: str = proto.Field( + proto.STRING, + number=181260274, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + optional=True, + ) + + +class InstantSnapshotAggregatedList(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + id (str): + [Output Only] Unique identifier for the resource; defined by + the server. + + This field is a member of `oneof`_ ``_id``. + items (MutableMapping[str, google.cloud.compute_v1.types.InstantSnapshotsScopedList]): + A list of InstantSnapshotsScopedList + resources. + kind (str): + [Output Only] Type of resource. Always + compute#instantSnapshotAggregatedList for aggregated lists + of instantSnapshots. + + This field is a member of `oneof`_ ``_kind``. + next_page_token (str): + [Output Only] This token allows you to get the next page of + results for list requests. If the number of results is + larger than maxResults, use the nextPageToken as a value for + the query parameter pageToken in the next list request. + Subsequent list requests will have their own nextPageToken + to continue paging through the results. + + This field is a member of `oneof`_ ``_next_page_token``. + self_link (str): + [Output Only] Server-defined URL for this resource. + + This field is a member of `oneof`_ ``_self_link``. + unreachables (MutableSequence[str]): + [Output Only] Unreachable resources. + warning (google.cloud.compute_v1.types.Warning): + [Output Only] Informational warning message. + + This field is a member of `oneof`_ ``_warning``. + """ + + @property + def raw_page(self): + return self + + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + items: MutableMapping[str, "InstantSnapshotsScopedList"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=100526016, + message="InstantSnapshotsScopedList", + ) + kind: str = proto.Field( + proto.STRING, + number=3292052, + optional=True, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=79797525, + optional=True, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + unreachables: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=243372063, + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + +class InstantSnapshotList(proto.Message): + r"""Contains a list of InstantSnapshot resources. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + id (str): + [Output Only] Unique identifier for the resource; defined by + the server. + + This field is a member of `oneof`_ ``_id``. + items (MutableSequence[google.cloud.compute_v1.types.InstantSnapshot]): + A list of InstantSnapshot resources. + kind (str): + Type of resource. + + This field is a member of `oneof`_ ``_kind``. + next_page_token (str): + [Output Only] This token allows you to get the next page of + results for list requests. If the number of results is + larger than maxResults, use the nextPageToken as a value for + the query parameter pageToken in the next list request. + Subsequent list requests will have their own nextPageToken + to continue paging through the results. + + This field is a member of `oneof`_ ``_next_page_token``. + self_link (str): + [Output Only] Server-defined URL for this resource. + + This field is a member of `oneof`_ ``_self_link``. + warning (google.cloud.compute_v1.types.Warning): + [Output Only] Informational warning message. + + This field is a member of `oneof`_ ``_warning``. + """ + + @property + def raw_page(self): + return self + + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + items: MutableSequence["InstantSnapshot"] = proto.RepeatedField( + proto.MESSAGE, + number=100526016, + message="InstantSnapshot", + ) + kind: str = proto.Field( + proto.STRING, + number=3292052, + optional=True, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=79797525, + optional=True, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + +class InstantSnapshotResourceStatus(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + storage_size_bytes (int): + [Output Only] The storage size of this instant snapshot. + + This field is a member of `oneof`_ ``_storage_size_bytes``. + """ + + storage_size_bytes: int = proto.Field( + proto.INT64, + number=387548913, + optional=True, + ) + + +class InstantSnapshotsScopedList(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instant_snapshots (MutableSequence[google.cloud.compute_v1.types.InstantSnapshot]): + [Output Only] A list of instantSnapshots contained in this + scope. + warning (google.cloud.compute_v1.types.Warning): + [Output Only] Informational warning which replaces the list + of instantSnapshots when the list is empty. + + This field is a member of `oneof`_ ``_warning``. + """ + + instant_snapshots: MutableSequence["InstantSnapshot"] = proto.RepeatedField( + proto.MESSAGE, + number=329637457, + message="InstantSnapshot", + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + class Int64RangeMatch(proto.Message): r"""HttpRouteRuleMatch criteria for field values that must stay within the specified integer range. @@ -48806,7 +50136,11 @@ class ListAcceleratorTypesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. zone (str): @@ -48935,9 +50269,166 @@ class ListAddressesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + + +class ListAssociationsFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.ListAssociations. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + target_resource (str): + The target resource to list associations. It + is an organization, or a folder. + + This field is a member of `oneof`_ ``_target_resource``. + """ + + target_resource: str = proto.Field( + proto.STRING, + number=467318524, + optional=True, + ) + + +class ListAutoscalersRequest(proto.Message): + r"""A request message for Autoscalers.List. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. Most Compute resources support two types of filter + expressions: expressions that support regular expressions + and expressions that follow API improvement proposal + AIP-160. These two types of filter expressions cannot be + mixed in one request. If you want to use AIP-160, your + expression must specify the field name, an operator, and the + value that you want to use for filtering. The value must be + a string, a number, or a boolean. The operator must be + either ``=``, ``!=``, ``>``, ``<``, ``<=``, ``>=`` or ``:``. + For example, if you are filtering Compute Engine instances, + you can exclude instances named ``example-instance`` by + specifying ``name != example-instance``. The ``:*`` + comparison can be used to test whether a key has been + defined. For example, to find all objects with ``owner`` + label use: ``labels.owner:*`` You can also filter nested + fields. For example, you could specify + ``scheduling.automaticRestart = false`` to include instances + only if they are not scheduled for automatic restarts. You + can use filtering on nested fields to filter based on + resource labels. To filter on multiple expressions, provide + each separate expression within parentheses. For example: + ``(scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake")`` + By default, each expression is an ``AND`` expression. + However, you can include ``AND`` and ``OR`` expressions + explicitly. For example: + ``(cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true)`` + If you want to use a regular expression, use the ``eq`` + (equal) or ``ne`` (not equal) operator against a single + un-parenthesized expression with or without quotes or + against multiple parenthesized expressions. Examples: + ``fieldname eq unquoted literal`` + ``fieldname eq 'single quoted literal'`` + ``fieldname eq "double quoted literal"`` + ``(fieldname1 eq literal) (fieldname2 ne "literal")`` The + literal value is interpreted as a regular expression using + Google RE2 library syntax. The literal value must match the + entire field. For example, to filter for instances that do + not end with name "instance", you would use + ``name ne .*instance``. You cannot combine constraints on + multiple fields using regular expressions. + + This field is a member of `oneof`_ ``_filter``. + max_results (int): + The maximum number of results per page that should be + returned. If the number of available results is larger than + ``maxResults``, Compute Engine returns a ``nextPageToken`` + that can be used to get the next page of results in + subsequent list requests. Acceptable values are ``0`` to + ``500``, inclusive. (Default: ``500``) + + This field is a member of `oneof`_ ``_max_results``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. You can also sort results in descending order based on + the creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Project ID for this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + Name of the zone for this request. """ filter: str = proto.Field( @@ -48964,41 +50455,20 @@ class ListAddressesRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - - -class ListAssociationsFirewallPolicyRequest(proto.Message): - r"""A request message for FirewallPolicies.ListAssociations. See - the method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - target_resource (str): - The target resource to list associations. It - is an organization, or a folder. - - This field is a member of `oneof`_ ``_target_resource``. - """ - - target_resource: str = proto.Field( + zone: str = proto.Field( proto.STRING, - number=467318524, - optional=True, + number=3744684, ) -class ListAutoscalersRequest(proto.Message): - r"""A request message for Autoscalers.List. See the method +class ListAvailableFeaturesRegionSslPoliciesRequest(proto.Message): + r"""A request message for + RegionSslPolicies.ListAvailableFeatures. See the method description for details. @@ -49079,14 +50549,18 @@ class ListAutoscalersRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - Name of the zone for this request. """ filter: str = proto.Field( @@ -49113,21 +50587,20 @@ class ListAutoscalersRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListAvailableFeaturesRegionSslPoliciesRequest(proto.Message): - r"""A request message for - RegionSslPolicies.ListAvailableFeatures. See the method - description for details. +class ListAvailableFeaturesSslPoliciesRequest(proto.Message): + r"""A request message for SslPolicies.ListAvailableFeatures. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -49207,12 +50680,14 @@ class ListAvailableFeaturesRegionSslPoliciesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -49241,10 +50716,6 @@ class ListAvailableFeaturesRegionSslPoliciesRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -49252,9 +50723,9 @@ class ListAvailableFeaturesRegionSslPoliciesRequest(proto.Message): ) -class ListAvailableFeaturesSslPoliciesRequest(proto.Message): - r"""A request message for SslPolicies.ListAvailableFeatures. See - the method description for details. +class ListBackendBucketsRequest(proto.Message): + r"""A request message for BackendBuckets.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -49337,7 +50808,11 @@ class ListAvailableFeaturesSslPoliciesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -49373,8 +50848,8 @@ class ListAvailableFeaturesSslPoliciesRequest(proto.Message): ) -class ListBackendBucketsRequest(proto.Message): - r"""A request message for BackendBuckets.List. See the method +class ListBackendServicesRequest(proto.Message): + r"""A request message for BackendServices.List. See the method description for details. @@ -49458,7 +50933,11 @@ class ListBackendBucketsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -49494,8 +50973,8 @@ class ListBackendBucketsRequest(proto.Message): ) -class ListBackendServicesRequest(proto.Message): - r"""A request message for BackendServices.List. See the method +class ListDiskTypesRequest(proto.Message): + r"""A request message for DiskTypes.List. See the method description for details. @@ -49579,9 +51058,15 @@ class ListBackendServicesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of the zone for this request. """ filter: str = proto.Field( @@ -49613,11 +51098,15 @@ class ListBackendServicesRequest(proto.Message): number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListDiskTypesRequest(proto.Message): - r"""A request message for DiskTypes.List. See the method - description for details. +class ListDisksRequest(proto.Message): + r"""A request message for Disks.List. See the method description + for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -49700,7 +51189,11 @@ class ListDiskTypesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. zone (str): @@ -49742,9 +51235,9 @@ class ListDiskTypesRequest(proto.Message): ) -class ListDisksRequest(proto.Message): - r"""A request message for Disks.List. See the method description - for details. +class ListErrorsInstanceGroupManagersRequest(proto.Message): + r"""A request message for InstanceGroupManagers.ListErrors. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -49794,6 +51287,11 @@ class ListDisksRequest(proto.Message): multiple fields using regular expressions. This field is a member of `oneof`_ ``_filter``. + instance_group_manager (str): + The name of the managed instance group. It must be a string + that meets the requirements in RFC1035, or an unsigned long + integer: must match regexp pattern: + (?:`a-z `__?)|1-9{0,19}. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -49827,11 +51325,17 @@ class ListDisksRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. zone (str): - The name of the zone for this request. + The name of the zone where the managed + instance group is located. It should conform to + RFC1035. """ filter: str = proto.Field( @@ -49839,6 +51343,10 @@ class ListDisksRequest(proto.Message): number=336120696, optional=True, ) + instance_group_manager: str = proto.Field( + proto.STRING, + number=249363395, + ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -49869,9 +51377,9 @@ class ListDisksRequest(proto.Message): ) -class ListErrorsInstanceGroupManagersRequest(proto.Message): - r"""A request message for InstanceGroupManagers.ListErrors. See - the method description for details. +class ListErrorsRegionInstanceGroupManagersRequest(proto.Message): + r"""A request message for RegionInstanceGroupManagers.ListErrors. + See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -49956,16 +51464,19 @@ class ListErrorsInstanceGroupManagersRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region scoping this request. This + should conform to RFC1035. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone where the managed - instance group is located. It should conform to - RFC1035. """ filter: str = proto.Field( @@ -49996,20 +51507,20 @@ class ListErrorsInstanceGroupManagersRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListErrorsRegionInstanceGroupManagersRequest(proto.Message): - r"""A request message for RegionInstanceGroupManagers.ListErrors. - See the method description for details. +class ListExternalVpnGatewaysRequest(proto.Message): + r"""A request message for ExternalVpnGateways.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -50059,11 +51570,6 @@ class ListErrorsRegionInstanceGroupManagersRequest(proto.Message): multiple fields using regular expressions. This field is a member of `oneof`_ ``_filter``. - instance_group_manager (str): - The name of the managed instance group. It must be a string - that meets the requirements in RFC1035, or an unsigned long - integer: must match regexp pattern: - (?:`a-z `__?)|1-9{0,19}. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -50094,13 +51600,14 @@ class ListErrorsRegionInstanceGroupManagersRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region scoping this request. This - should conform to RFC1035. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -50110,10 +51617,6 @@ class ListErrorsRegionInstanceGroupManagersRequest(proto.Message): number=336120696, optional=True, ) - instance_group_manager: str = proto.Field( - proto.STRING, - number=249363395, - ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -50133,10 +51636,6 @@ class ListErrorsRegionInstanceGroupManagersRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -50144,9 +51643,9 @@ class ListErrorsRegionInstanceGroupManagersRequest(proto.Message): ) -class ListExternalVpnGatewaysRequest(proto.Message): - r"""A request message for ExternalVpnGateways.List. See the - method description for details. +class ListFirewallPoliciesRequest(proto.Message): + r"""A request message for FirewallPolicies.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -50224,12 +51723,21 @@ class ListExternalVpnGatewaysRequest(proto.Message): the next page of results. This field is a member of `oneof`_ ``_page_token``. - project (str): - Project ID for this request. + parent_id (str): + Parent ID for this request. The ID can be either be + "folders/[FOLDER_ID]" if the parent is a folder or + "organizations/[ORGANIZATION_ID]" if the parent is an + organization. + + This field is a member of `oneof`_ ``_parent_id``. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -50254,9 +51762,10 @@ class ListExternalVpnGatewaysRequest(proto.Message): number=19994697, optional=True, ) - project: str = proto.Field( + parent_id: str = proto.Field( proto.STRING, - number=227560217, + number=459714768, + optional=True, ) return_partial_success: bool = proto.Field( proto.BOOL, @@ -50265,8 +51774,8 @@ class ListExternalVpnGatewaysRequest(proto.Message): ) -class ListFirewallPoliciesRequest(proto.Message): - r"""A request message for FirewallPolicies.List. See the method +class ListFirewallsRequest(proto.Message): + r"""A request message for Firewalls.List. See the method description for details. @@ -50345,17 +51854,16 @@ class ListFirewallPoliciesRequest(proto.Message): the next page of results. This field is a member of `oneof`_ ``_page_token``. - parent_id (str): - Parent ID for this request. The ID can be either be - "folders/[FOLDER_ID]" if the parent is a folder or - "organizations/[ORGANIZATION_ID]" if the parent is an - organization. - - This field is a member of `oneof`_ ``_parent_id``. + project (str): + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -50380,10 +51888,9 @@ class ListFirewallPoliciesRequest(proto.Message): number=19994697, optional=True, ) - parent_id: str = proto.Field( + project: str = proto.Field( proto.STRING, - number=459714768, - optional=True, + number=227560217, ) return_partial_success: bool = proto.Field( proto.BOOL, @@ -50392,8 +51899,8 @@ class ListFirewallPoliciesRequest(proto.Message): ) -class ListFirewallsRequest(proto.Message): - r"""A request message for Firewalls.List. See the method +class ListForwardingRulesRequest(proto.Message): + r"""A request message for ForwardingRules.List. See the method description for details. @@ -50474,10 +51981,16 @@ class ListFirewallsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -50506,6 +52019,10 @@ class ListFirewallsRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -50513,8 +52030,8 @@ class ListFirewallsRequest(proto.Message): ) -class ListForwardingRulesRequest(proto.Message): - r"""A request message for ForwardingRules.List. See the method +class ListGlobalAddressesRequest(proto.Message): + r"""A request message for GlobalAddresses.List. See the method description for details. @@ -50595,12 +52112,14 @@ class ListForwardingRulesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -50629,10 +52148,6 @@ class ListForwardingRulesRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -50640,9 +52155,9 @@ class ListForwardingRulesRequest(proto.Message): ) -class ListGlobalAddressesRequest(proto.Message): - r"""A request message for GlobalAddresses.List. See the method - description for details. +class ListGlobalForwardingRulesRequest(proto.Message): + r"""A request message for GlobalForwardingRules.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -50725,7 +52240,11 @@ class ListGlobalAddressesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -50761,9 +52280,9 @@ class ListGlobalAddressesRequest(proto.Message): ) -class ListGlobalForwardingRulesRequest(proto.Message): - r"""A request message for GlobalForwardingRules.List. See the - method description for details. +class ListGlobalNetworkEndpointGroupsRequest(proto.Message): + r"""A request message for GlobalNetworkEndpointGroups.List. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -50846,7 +52365,11 @@ class ListGlobalForwardingRulesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -50882,9 +52405,9 @@ class ListGlobalForwardingRulesRequest(proto.Message): ) -class ListGlobalNetworkEndpointGroupsRequest(proto.Message): - r"""A request message for GlobalNetworkEndpointGroups.List. See - the method description for details. +class ListGlobalOperationsRequest(proto.Message): + r"""A request message for GlobalOperations.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -50967,7 +52490,11 @@ class ListGlobalNetworkEndpointGroupsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -51003,9 +52530,9 @@ class ListGlobalNetworkEndpointGroupsRequest(proto.Message): ) -class ListGlobalOperationsRequest(proto.Message): - r"""A request message for GlobalOperations.List. See the method - description for details. +class ListGlobalOrganizationOperationsRequest(proto.Message): + r"""A request message for GlobalOrganizationOperations.List. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -51083,12 +52610,18 @@ class ListGlobalOperationsRequest(proto.Message): the next page of results. This field is a member of `oneof`_ ``_page_token``. - project (str): - Project ID for this request. + parent_id (str): + Parent ID for this request. + + This field is a member of `oneof`_ ``_parent_id``. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -51113,9 +52646,10 @@ class ListGlobalOperationsRequest(proto.Message): number=19994697, optional=True, ) - project: str = proto.Field( + parent_id: str = proto.Field( proto.STRING, - number=227560217, + number=459714768, + optional=True, ) return_partial_success: bool = proto.Field( proto.BOOL, @@ -51124,8 +52658,8 @@ class ListGlobalOperationsRequest(proto.Message): ) -class ListGlobalOrganizationOperationsRequest(proto.Message): - r"""A request message for GlobalOrganizationOperations.List. See +class ListGlobalPublicDelegatedPrefixesRequest(proto.Message): + r"""A request message for GlobalPublicDelegatedPrefixes.List. See the method description for details. @@ -51204,14 +52738,16 @@ class ListGlobalOrganizationOperationsRequest(proto.Message): the next page of results. This field is a member of `oneof`_ ``_page_token``. - parent_id (str): - Parent ID for this request. - - This field is a member of `oneof`_ ``_parent_id``. + project (str): + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -51236,10 +52772,9 @@ class ListGlobalOrganizationOperationsRequest(proto.Message): number=19994697, optional=True, ) - parent_id: str = proto.Field( + project: str = proto.Field( proto.STRING, - number=459714768, - optional=True, + number=227560217, ) return_partial_success: bool = proto.Field( proto.BOOL, @@ -51248,9 +52783,9 @@ class ListGlobalOrganizationOperationsRequest(proto.Message): ) -class ListGlobalPublicDelegatedPrefixesRequest(proto.Message): - r"""A request message for GlobalPublicDelegatedPrefixes.List. See - the method description for details. +class ListHealthChecksRequest(proto.Message): + r"""A request message for HealthChecks.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -51333,7 +52868,11 @@ class ListGlobalPublicDelegatedPrefixesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -51369,9 +52908,9 @@ class ListGlobalPublicDelegatedPrefixesRequest(proto.Message): ) -class ListHealthChecksRequest(proto.Message): - r"""A request message for HealthChecks.List. See the method - description for details. +class ListImagesRequest(proto.Message): + r"""A request message for Images.List. See the method description + for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -51454,7 +52993,11 @@ class ListHealthChecksRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -51490,9 +53033,9 @@ class ListHealthChecksRequest(proto.Message): ) -class ListImagesRequest(proto.Message): - r"""A request message for Images.List. See the method description - for details. +class ListInstanceGroupManagersRequest(proto.Message): + r"""A request message for InstanceGroupManagers.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -51575,9 +53118,16 @@ class ListImagesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of the zone where the managed + instance group is located. """ filter: str = proto.Field( @@ -51609,11 +53159,15 @@ class ListImagesRequest(proto.Message): number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListInstanceGroupManagersRequest(proto.Message): - r"""A request message for InstanceGroupManagers.List. See the - method description for details. +class ListInstanceGroupsRequest(proto.Message): + r"""A request message for InstanceGroups.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -51696,12 +53250,16 @@ class ListInstanceGroupManagersRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. zone (str): - The name of the zone where the managed - instance group is located. + The name of the zone where the instance group + is located. """ filter: str = proto.Field( @@ -51739,8 +53297,8 @@ class ListInstanceGroupManagersRequest(proto.Message): ) -class ListInstanceGroupsRequest(proto.Message): - r"""A request message for InstanceGroups.List. See the method +class ListInstanceTemplatesRequest(proto.Message): + r"""A request message for InstanceTemplates.List. See the method description for details. @@ -51824,12 +53382,13 @@ class ListInstanceGroupsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone where the instance group - is located. """ filter: str = proto.Field( @@ -51861,15 +53420,11 @@ class ListInstanceGroupsRequest(proto.Message): number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListInstanceTemplatesRequest(proto.Message): - r"""A request message for InstanceTemplates.List. See the method - description for details. +class ListInstancesInstanceGroupsRequest(proto.Message): + r"""A request message for InstanceGroups.ListInstances. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -51919,6 +53474,11 @@ class ListInstanceTemplatesRequest(proto.Message): multiple fields using regular expressions. This field is a member of `oneof`_ ``_filter``. + instance_group (str): + The name of the instance group from which you + want to generate a list of included instances. + instance_groups_list_instances_request_resource (google.cloud.compute_v1.types.InstanceGroupsListInstancesRequest): + The body resource for this request max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -51952,9 +53512,16 @@ class ListInstanceTemplatesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of the zone where the instance group + is located. """ filter: str = proto.Field( @@ -51962,6 +53529,15 @@ class ListInstanceTemplatesRequest(proto.Message): number=336120696, optional=True, ) + instance_group: str = proto.Field( + proto.STRING, + number=81095253, + ) + instance_groups_list_instances_request_resource: "InstanceGroupsListInstancesRequest" = proto.Field( + proto.MESSAGE, + number=476255263, + message="InstanceGroupsListInstancesRequest", + ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -51986,11 +53562,15 @@ class ListInstanceTemplatesRequest(proto.Message): number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListInstancesInstanceGroupsRequest(proto.Message): - r"""A request message for InstanceGroups.ListInstances. See the - method description for details. +class ListInstancesRegionInstanceGroupsRequest(proto.Message): + r"""A request message for RegionInstanceGroups.ListInstances. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -52041,10 +53621,8 @@ class ListInstancesInstanceGroupsRequest(proto.Message): This field is a member of `oneof`_ ``_filter``. instance_group (str): - The name of the instance group from which you - want to generate a list of included instances. - instance_groups_list_instances_request_resource (google.cloud.compute_v1.types.InstanceGroupsListInstancesRequest): - The body resource for this request + Name of the regional instance group for which + we want to list the instances. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -52075,15 +53653,20 @@ class ListInstancesInstanceGroupsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region scoping this request. + region_instance_groups_list_instances_request_resource (google.cloud.compute_v1.types.RegionInstanceGroupsListInstancesRequest): + The body resource for this request return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone where the instance group - is located. """ filter: str = proto.Field( @@ -52095,11 +53678,6 @@ class ListInstancesInstanceGroupsRequest(proto.Message): proto.STRING, number=81095253, ) - instance_groups_list_instances_request_resource: "InstanceGroupsListInstancesRequest" = proto.Field( - proto.MESSAGE, - number=476255263, - message="InstanceGroupsListInstancesRequest", - ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -52119,20 +53697,25 @@ class ListInstancesInstanceGroupsRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + region_instance_groups_list_instances_request_resource: "RegionInstanceGroupsListInstancesRequest" = proto.Field( + proto.MESSAGE, + number=48239828, + message="RegionInstanceGroupsListInstancesRequest", + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListInstancesRegionInstanceGroupsRequest(proto.Message): - r"""A request message for RegionInstanceGroups.ListInstances. See - the method description for details. +class ListInstancesRequest(proto.Message): + r"""A request message for Instances.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -52182,9 +53765,6 @@ class ListInstancesRegionInstanceGroupsRequest(proto.Message): multiple fields using regular expressions. This field is a member of `oneof`_ ``_filter``. - instance_group (str): - Name of the regional instance group for which - we want to list the instances. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -52215,16 +53795,18 @@ class ListInstancesRegionInstanceGroupsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region scoping this request. - region_instance_groups_list_instances_request_resource (google.cloud.compute_v1.types.RegionInstanceGroupsListInstancesRequest): - The body resource for this request return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of the zone for this request. """ filter: str = proto.Field( @@ -52232,10 +53814,6 @@ class ListInstancesRegionInstanceGroupsRequest(proto.Message): number=336120696, optional=True, ) - instance_group: str = proto.Field( - proto.STRING, - number=81095253, - ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -52255,24 +53833,19 @@ class ListInstancesRegionInstanceGroupsRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) - region_instance_groups_list_instances_request_resource: "RegionInstanceGroupsListInstancesRequest" = proto.Field( - proto.MESSAGE, - number=48239828, - message="RegionInstanceGroupsListInstancesRequest", - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListInstancesRequest(proto.Message): - r"""A request message for Instances.List. See the method +class ListInstantSnapshotsRequest(proto.Message): + r"""A request message for InstantSnapshots.List. See the method description for details. @@ -52356,7 +53929,11 @@ class ListInstancesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. zone (str): @@ -52485,7 +54062,11 @@ class ListInterconnectAttachmentsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -52610,7 +54191,11 @@ class ListInterconnectLocationsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -52731,7 +54316,11 @@ class ListInterconnectRemoteLocationsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -52852,7 +54441,11 @@ class ListInterconnectsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -52973,7 +54566,11 @@ class ListLicensesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -53094,7 +54691,11 @@ class ListMachineImagesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -53215,7 +54816,11 @@ class ListMachineTypesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. zone (str): @@ -53345,7 +54950,11 @@ class ListManagedInstancesInstanceGroupManagersRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. zone (str): @@ -53482,7 +55091,11 @@ class ListManagedInstancesRegionInstanceGroupManagersRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -53613,7 +55226,11 @@ class ListNetworkAttachmentsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -53738,7 +55355,11 @@ class ListNetworkEndpointGroupsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. zone (str): @@ -53873,7 +55494,11 @@ class ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -54006,7 +55631,11 @@ class ListNetworkEndpointsNetworkEndpointGroupsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. zone (str): @@ -54154,7 +55783,11 @@ class ListNetworkEndpointsRegionNetworkEndpointGroupsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -54283,7 +55916,11 @@ class ListNetworkFirewallPoliciesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -54404,7 +56041,11 @@ class ListNetworksRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -54525,7 +56166,11 @@ class ListNodeGroupsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. zone (str): @@ -54654,7 +56299,11 @@ class ListNodeTemplatesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -54779,7 +56428,11 @@ class ListNodeTypesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. zone (str): @@ -54909,7 +56562,11 @@ class ListNodesNodeGroupsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. zone (str): @@ -55042,7 +56699,11 @@ class ListPacketMirroringsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -55186,7 +56847,11 @@ class ListPeeringRoutesNetworksRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -55346,7 +57011,11 @@ class ListPerInstanceConfigsInstanceGroupManagersRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. zone (str): @@ -55486,7 +57155,11 @@ class ListPerInstanceConfigsRegionInstanceGroupManagersRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -55616,7 +57289,11 @@ class ListPreconfiguredExpressionSetsSecurityPoliciesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -55737,7 +57414,138 @@ class ListPublicAdvertisedPrefixesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + + +class ListPublicDelegatedPrefixesRequest(proto.Message): + r"""A request message for PublicDelegatedPrefixes.List. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. Most Compute resources support two types of filter + expressions: expressions that support regular expressions + and expressions that follow API improvement proposal + AIP-160. These two types of filter expressions cannot be + mixed in one request. If you want to use AIP-160, your + expression must specify the field name, an operator, and the + value that you want to use for filtering. The value must be + a string, a number, or a boolean. The operator must be + either ``=``, ``!=``, ``>``, ``<``, ``<=``, ``>=`` or ``:``. + For example, if you are filtering Compute Engine instances, + you can exclude instances named ``example-instance`` by + specifying ``name != example-instance``. The ``:*`` + comparison can be used to test whether a key has been + defined. For example, to find all objects with ``owner`` + label use: ``labels.owner:*`` You can also filter nested + fields. For example, you could specify + ``scheduling.automaticRestart = false`` to include instances + only if they are not scheduled for automatic restarts. You + can use filtering on nested fields to filter based on + resource labels. To filter on multiple expressions, provide + each separate expression within parentheses. For example: + ``(scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake")`` + By default, each expression is an ``AND`` expression. + However, you can include ``AND`` and ``OR`` expressions + explicitly. For example: + ``(cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true)`` + If you want to use a regular expression, use the ``eq`` + (equal) or ``ne`` (not equal) operator against a single + un-parenthesized expression with or without quotes or + against multiple parenthesized expressions. Examples: + ``fieldname eq unquoted literal`` + ``fieldname eq 'single quoted literal'`` + ``fieldname eq "double quoted literal"`` + ``(fieldname1 eq literal) (fieldname2 ne "literal")`` The + literal value is interpreted as a regular expression using + Google RE2 library syntax. The literal value must match the + entire field. For example, to filter for instances that do + not end with name "instance", you would use + ``name ne .*instance``. You cannot combine constraints on + multiple fields using regular expressions. + + This field is a member of `oneof`_ ``_filter``. + max_results (int): + The maximum number of results per page that should be + returned. If the number of available results is larger than + ``maxResults``, Compute Engine returns a ``nextPageToken`` + that can be used to get the next page of results in + subsequent list requests. Acceptable values are ``0`` to + ``500``, inclusive. (Default: ``500``) + + This field is a member of `oneof`_ ``_max_results``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. You can also sort results in descending order based on + the creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Project ID for this request. + region (str): + Name of the region of this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -55766,6 +57574,10 @@ class ListPublicAdvertisedPrefixesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -55773,9 +57585,9 @@ class ListPublicAdvertisedPrefixesRequest(proto.Message): ) -class ListPublicDelegatedPrefixesRequest(proto.Message): - r"""A request message for PublicDelegatedPrefixes.List. See the - method description for details. +class ListReferrersInstancesRequest(proto.Message): + r"""A request message for Instances.ListReferrers. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -55825,6 +57637,10 @@ class ListPublicDelegatedPrefixesRequest(proto.Message): multiple fields using regular expressions. This field is a member of `oneof`_ ``_filter``. + instance (str): + Name of the target instance scoping this + request, or '-' if the request should span over + all instances in the container. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -55855,14 +57671,18 @@ class ListPublicDelegatedPrefixesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region of this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of the zone for this request. """ filter: str = proto.Field( @@ -55870,6 +57690,10 @@ class ListPublicDelegatedPrefixesRequest(proto.Message): number=336120696, optional=True, ) + instance: str = proto.Field( + proto.STRING, + number=18257045, + ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -55889,19 +57713,19 @@ class ListPublicDelegatedPrefixesRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListReferrersInstancesRequest(proto.Message): - r"""A request message for Instances.ListReferrers. See the method +class ListRegionAutoscalersRequest(proto.Message): + r"""A request message for RegionAutoscalers.List. See the method description for details. @@ -55952,10 +57776,6 @@ class ListReferrersInstancesRequest(proto.Message): multiple fields using regular expressions. This field is a member of `oneof`_ ``_filter``. - instance (str): - Name of the target instance scoping this - request, or '-' if the request should span over - all instances in the container. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -55986,14 +57806,18 @@ class ListReferrersInstancesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone for this request. """ filter: str = proto.Field( @@ -56001,10 +57825,6 @@ class ListReferrersInstancesRequest(proto.Message): number=336120696, optional=True, ) - instance: str = proto.Field( - proto.STRING, - number=18257045, - ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -56024,20 +57844,20 @@ class ListReferrersInstancesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListRegionAutoscalersRequest(proto.Message): - r"""A request message for RegionAutoscalers.List. See the method - description for details. +class ListRegionBackendServicesRequest(proto.Message): + r"""A request message for RegionBackendServices.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -56122,7 +57942,11 @@ class ListRegionAutoscalersRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -56162,9 +57986,9 @@ class ListRegionAutoscalersRequest(proto.Message): ) -class ListRegionBackendServicesRequest(proto.Message): - r"""A request message for RegionBackendServices.List. See the - method description for details. +class ListRegionCommitmentsRequest(proto.Message): + r"""A request message for RegionCommitments.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -56245,11 +58069,15 @@ class ListRegionBackendServicesRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -56289,8 +58117,8 @@ class ListRegionBackendServicesRequest(proto.Message): ) -class ListRegionCommitmentsRequest(proto.Message): - r"""A request message for RegionCommitments.List. See the method +class ListRegionDiskTypesRequest(proto.Message): + r"""A request message for RegionDiskTypes.List. See the method description for details. @@ -56372,11 +58200,15 @@ class ListRegionCommitmentsRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region for this request. + The name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -56416,8 +58248,8 @@ class ListRegionCommitmentsRequest(proto.Message): ) -class ListRegionDiskTypesRequest(proto.Message): - r"""A request message for RegionDiskTypes.List. See the method +class ListRegionDisksRequest(proto.Message): + r"""A request message for RegionDisks.List. See the method description for details. @@ -56499,11 +58331,15 @@ class ListRegionDiskTypesRequest(proto.Message): project (str): Project ID for this request. region (str): - The name of the region for this request. + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -56543,9 +58379,9 @@ class ListRegionDiskTypesRequest(proto.Message): ) -class ListRegionDisksRequest(proto.Message): - r"""A request message for RegionDisks.List. See the method - description for details. +class ListRegionHealthCheckServicesRequest(proto.Message): + r"""A request message for RegionHealthCheckServices.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -56626,11 +58462,15 @@ class ListRegionDisksRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region for this request. + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -56670,9 +58510,9 @@ class ListRegionDisksRequest(proto.Message): ) -class ListRegionHealthCheckServicesRequest(proto.Message): - r"""A request message for RegionHealthCheckServices.List. See the - method description for details. +class ListRegionHealthChecksRequest(proto.Message): + r"""A request message for RegionHealthChecks.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -56757,7 +58597,11 @@ class ListRegionHealthCheckServicesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -56797,9 +58641,9 @@ class ListRegionHealthCheckServicesRequest(proto.Message): ) -class ListRegionHealthChecksRequest(proto.Message): - r"""A request message for RegionHealthChecks.List. See the method - description for details. +class ListRegionInstanceGroupManagersRequest(proto.Message): + r"""A request message for RegionInstanceGroupManagers.List. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -56884,7 +58728,11 @@ class ListRegionHealthChecksRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -56924,9 +58772,9 @@ class ListRegionHealthChecksRequest(proto.Message): ) -class ListRegionInstanceGroupManagersRequest(proto.Message): - r"""A request message for RegionInstanceGroupManagers.List. See - the method description for details. +class ListRegionInstanceGroupsRequest(proto.Message): + r"""A request message for RegionInstanceGroups.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -57011,7 +58859,11 @@ class ListRegionInstanceGroupManagersRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -57051,8 +58903,8 @@ class ListRegionInstanceGroupManagersRequest(proto.Message): ) -class ListRegionInstanceGroupsRequest(proto.Message): - r"""A request message for RegionInstanceGroups.List. See the +class ListRegionInstanceTemplatesRequest(proto.Message): + r"""A request message for RegionInstanceTemplates.List. See the method description for details. @@ -57134,11 +58986,15 @@ class ListRegionInstanceGroupsRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + The name of the regions for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -57178,8 +59034,8 @@ class ListRegionInstanceGroupsRequest(proto.Message): ) -class ListRegionInstanceTemplatesRequest(proto.Message): - r"""A request message for RegionInstanceTemplates.List. See the +class ListRegionInstantSnapshotsRequest(proto.Message): + r"""A request message for RegionInstantSnapshots.List. See the method description for details. @@ -57261,11 +59117,15 @@ class ListRegionInstanceTemplatesRequest(proto.Message): project (str): Project ID for this request. region (str): - The name of the regions for this request. + The name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -57394,7 +59254,11 @@ class ListRegionNetworkEndpointGroupsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -57521,7 +59385,11 @@ class ListRegionNetworkFirewallPoliciesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -57648,7 +59516,11 @@ class ListRegionNotificationEndpointsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -57775,7 +59647,11 @@ class ListRegionOperationsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -57902,7 +59778,11 @@ class ListRegionSecurityPoliciesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -58029,7 +59909,11 @@ class ListRegionSslCertificatesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -58156,7 +60040,11 @@ class ListRegionSslPoliciesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -58283,7 +60171,11 @@ class ListRegionTargetHttpProxiesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -58410,7 +60302,11 @@ class ListRegionTargetHttpsProxiesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -58537,7 +60433,11 @@ class ListRegionTargetTcpProxiesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -58664,7 +60564,11 @@ class ListRegionUrlMapsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -58791,7 +60695,11 @@ class ListRegionZonesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -58916,7 +60824,11 @@ class ListRegionsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -59037,7 +60949,11 @@ class ListReservationsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. zone (str): @@ -59166,7 +61082,11 @@ class ListResourcePoliciesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -59293,7 +61213,11 @@ class ListRoutersRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -59418,7 +61342,11 @@ class ListRoutesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -59539,7 +61467,11 @@ class ListSecurityPoliciesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -59662,7 +61594,11 @@ class ListServiceAttachmentsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -59787,7 +61723,11 @@ class ListSnapshotsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -59908,7 +61848,11 @@ class ListSslCertificatesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -60029,7 +61973,11 @@ class ListSslPoliciesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -60152,7 +62100,11 @@ class ListSubnetworksRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -60277,7 +62229,11 @@ class ListTargetGrpcProxiesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -60398,7 +62354,11 @@ class ListTargetHttpProxiesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -60519,7 +62479,11 @@ class ListTargetHttpsProxiesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -60640,7 +62604,11 @@ class ListTargetInstancesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. zone (str): @@ -60769,7 +62737,11 @@ class ListTargetPoolsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -60894,7 +62866,11 @@ class ListTargetSslProxiesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -61015,7 +62991,11 @@ class ListTargetTcpProxiesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -61138,7 +63118,11 @@ class ListTargetVpnGatewaysRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -61263,7 +63247,11 @@ class ListUrlMapsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -61384,7 +63372,11 @@ class ListUsableBackendServicesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -61509,7 +63501,11 @@ class ListUsableRegionBackendServicesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -61634,7 +63630,11 @@ class ListUsableSubnetworksRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -61757,7 +63757,11 @@ class ListVpnGatewaysRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -61884,7 +63888,11 @@ class ListVpnTunnelsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -62011,7 +64019,11 @@ class ListXpnHostsProjectsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -62139,7 +64151,11 @@ class ListZoneOperationsRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. zone (str): @@ -62266,7 +64282,11 @@ class ListZonesRequest(proto.Message): return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The - default value is false. + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. """ @@ -74111,6 +76131,14 @@ class Project(proto.Message): .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + cloud_armor_tier (str): + [Output Only] The Cloud Armor tier for this project. It can + be one of the following values: CA_STANDARD, + CA_ENTERPRISE_PAYGO. If this field is not specified, it is + assumed to be CA_STANDARD. Check the CloudArmorTier enum for + the list of possible values. + + This field is a member of `oneof`_ ``_cloud_armor_tier``. common_instance_metadata (google.cloud.compute_v1.types.Metadata): Metadata key/value pairs available to all instances contained in this project. See Custom @@ -74189,6 +76217,27 @@ class Project(proto.Message): This field is a member of `oneof`_ ``_xpn_project_status``. """ + class CloudArmorTier(proto.Enum): + r"""[Output Only] The Cloud Armor tier for this project. It can be one + of the following values: CA_STANDARD, CA_ENTERPRISE_PAYGO. If this + field is not specified, it is assumed to be CA_STANDARD. + + Values: + UNDEFINED_CLOUD_ARMOR_TIER (0): + A value indicating that the enum field is not + set. + CA_ENTERPRISE_ANNUAL (219921116): + Enterprise tier protection billed annually. + CA_ENTERPRISE_PAYGO (453530323): + Enterprise tier protection billed monthly. + CA_STANDARD (13156734): + Standard protection. + """ + UNDEFINED_CLOUD_ARMOR_TIER = 0 + CA_ENTERPRISE_ANNUAL = 219921116 + CA_ENTERPRISE_PAYGO = 453530323 + CA_STANDARD = 13156734 + class DefaultNetworkTier(proto.Enum): r"""This signifies the default network tier used for configuring resources of the project and can only take the following values: @@ -74258,6 +76307,11 @@ class XpnProjectStatus(proto.Enum): HOST = 2223528 UNSPECIFIED_XPN_PROJECT_STATUS = 340393257 + cloud_armor_tier: str = proto.Field( + proto.STRING, + number=4427052, + optional=True, + ) common_instance_metadata: "Metadata" = proto.Field( proto.MESSAGE, number=185794117, @@ -74441,6 +76495,46 @@ class ProjectsListXpnHostsRequest(proto.Message): ) +class ProjectsSetCloudArmorTierRequest(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_armor_tier (str): + Managed protection tier to be set. + Check the CloudArmorTier enum for the list of + possible values. + + This field is a member of `oneof`_ ``_cloud_armor_tier``. + """ + + class CloudArmorTier(proto.Enum): + r"""Managed protection tier to be set. + + Values: + UNDEFINED_CLOUD_ARMOR_TIER (0): + A value indicating that the enum field is not + set. + CA_ENTERPRISE_ANNUAL (219921116): + Enterprise tier protection billed annually. + CA_ENTERPRISE_PAYGO (453530323): + Enterprise tier protection billed monthly. + CA_STANDARD (13156734): + Standard protection. + """ + UNDEFINED_CLOUD_ARMOR_TIER = 0 + CA_ENTERPRISE_ANNUAL = 219921116 + CA_ENTERPRISE_PAYGO = 453530323 + CA_STANDARD = 13156734 + + cloud_armor_tier: str = proto.Field( + proto.STRING, + number=4427052, + optional=True, + ) + + class ProjectsSetDefaultNetworkTierRequest(proto.Message): r""" @@ -87281,6 +89375,54 @@ class SetCertificateMapTargetSslProxyRequest(proto.Message): ) +class SetCloudArmorTierProjectRequest(proto.Message): + r"""A request message for Projects.SetCloudArmorTier. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Project ID for this request. + projects_set_cloud_armor_tier_request_resource (google.cloud.compute_v1.types.ProjectsSetCloudArmorTierRequest): + The body resource for this request + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + projects_set_cloud_armor_tier_request_resource: "ProjectsSetCloudArmorTierRequest" = proto.Field( + proto.MESSAGE, + number=77053391, + message="ProjectsSetCloudArmorTierRequest", + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + + class SetCommonInstanceMetadataOperationMetadata(proto.Message): r""" @@ -87917,6 +90059,40 @@ class SetIamPolicyInstanceTemplateRequest(proto.Message): ) +class SetIamPolicyInstantSnapshotRequest(proto.Message): + r"""A request message for InstantSnapshots.SetIamPolicy. See the + method description for details. + + Attributes: + project (str): + Project ID for this request. + resource (str): + Name or id of the resource for this request. + zone (str): + The name of the zone for this request. + zone_set_policy_request_resource (google.cloud.compute_v1.types.ZoneSetPolicyRequest): + The body resource for this request + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + zone_set_policy_request_resource: "ZoneSetPolicyRequest" = proto.Field( + proto.MESSAGE, + number=382082107, + message="ZoneSetPolicyRequest", + ) + + class SetIamPolicyLicenseRequest(proto.Message): r"""A request message for Licenses.SetIamPolicy. See the method description for details. @@ -88137,9 +90313,43 @@ class SetIamPolicyRegionBackendServiceRequest(proto.Message): ) -class SetIamPolicyRegionDiskRequest(proto.Message): - r"""A request message for RegionDisks.SetIamPolicy. See the - method description for details. +class SetIamPolicyRegionDiskRequest(proto.Message): + r"""A request message for RegionDisks.SetIamPolicy. See the + method description for details. + + Attributes: + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + region_set_policy_request_resource (google.cloud.compute_v1.types.RegionSetPolicyRequest): + The body resource for this request + resource (str): + Name or id of the resource for this request. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + region_set_policy_request_resource: "RegionSetPolicyRequest" = proto.Field( + proto.MESSAGE, + number=276489091, + message="RegionSetPolicyRequest", + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class SetIamPolicyRegionInstantSnapshotRequest(proto.Message): + r"""A request message for RegionInstantSnapshots.SetIamPolicy. + See the method description for details. Attributes: project (str): @@ -88701,64 +90911,272 @@ class SetLabelsForwardingRuleRequest(proto.Message): ) -class SetLabelsGlobalAddressRequest(proto.Message): - r"""A request message for GlobalAddresses.SetLabels. See the - method description for details. - - Attributes: - global_set_labels_request_resource (google.cloud.compute_v1.types.GlobalSetLabelsRequest): - The body resource for this request - project (str): - Project ID for this request. - resource (str): - Name or id of the resource for this request. - """ - - global_set_labels_request_resource: "GlobalSetLabelsRequest" = proto.Field( - proto.MESSAGE, - number=319917189, - message="GlobalSetLabelsRequest", - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - resource: str = proto.Field( - proto.STRING, - number=195806222, - ) - - -class SetLabelsGlobalForwardingRuleRequest(proto.Message): - r"""A request message for GlobalForwardingRules.SetLabels. See - the method description for details. - - Attributes: - global_set_labels_request_resource (google.cloud.compute_v1.types.GlobalSetLabelsRequest): - The body resource for this request - project (str): - Project ID for this request. - resource (str): - Name or id of the resource for this request. - """ - - global_set_labels_request_resource: "GlobalSetLabelsRequest" = proto.Field( - proto.MESSAGE, - number=319917189, - message="GlobalSetLabelsRequest", - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - resource: str = proto.Field( - proto.STRING, - number=195806222, - ) - - -class SetLabelsImageRequest(proto.Message): - r"""A request message for Images.SetLabels. See the method +class SetLabelsGlobalAddressRequest(proto.Message): + r"""A request message for GlobalAddresses.SetLabels. See the + method description for details. + + Attributes: + global_set_labels_request_resource (google.cloud.compute_v1.types.GlobalSetLabelsRequest): + The body resource for this request + project (str): + Project ID for this request. + resource (str): + Name or id of the resource for this request. + """ + + global_set_labels_request_resource: "GlobalSetLabelsRequest" = proto.Field( + proto.MESSAGE, + number=319917189, + message="GlobalSetLabelsRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class SetLabelsGlobalForwardingRuleRequest(proto.Message): + r"""A request message for GlobalForwardingRules.SetLabels. See + the method description for details. + + Attributes: + global_set_labels_request_resource (google.cloud.compute_v1.types.GlobalSetLabelsRequest): + The body resource for this request + project (str): + Project ID for this request. + resource (str): + Name or id of the resource for this request. + """ + + global_set_labels_request_resource: "GlobalSetLabelsRequest" = proto.Field( + proto.MESSAGE, + number=319917189, + message="GlobalSetLabelsRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class SetLabelsImageRequest(proto.Message): + r"""A request message for Images.SetLabels. See the method + description for details. + + Attributes: + global_set_labels_request_resource (google.cloud.compute_v1.types.GlobalSetLabelsRequest): + The body resource for this request + project (str): + Project ID for this request. + resource (str): + Name or id of the resource for this request. + """ + + global_set_labels_request_resource: "GlobalSetLabelsRequest" = proto.Field( + proto.MESSAGE, + number=319917189, + message="GlobalSetLabelsRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class SetLabelsInstanceRequest(proto.Message): + r"""A request message for Instances.SetLabels. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instance (str): + Name of the instance scoping this request. + instances_set_labels_request_resource (google.cloud.compute_v1.types.InstancesSetLabelsRequest): + The body resource for this request + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + zone (str): + The name of the zone for this request. + """ + + instance: str = proto.Field( + proto.STRING, + number=18257045, + ) + instances_set_labels_request_resource: "InstancesSetLabelsRequest" = proto.Field( + proto.MESSAGE, + number=207749344, + message="InstancesSetLabelsRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class SetLabelsInstantSnapshotRequest(proto.Message): + r"""A request message for InstantSnapshots.SetLabels. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + resource (str): + Name or id of the resource for this request. + zone (str): + The name of the zone for this request. + zone_set_labels_request_resource (google.cloud.compute_v1.types.ZoneSetLabelsRequest): + The body resource for this request + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + zone_set_labels_request_resource: "ZoneSetLabelsRequest" = proto.Field( + proto.MESSAGE, + number=364950798, + message="ZoneSetLabelsRequest", + ) + + +class SetLabelsInterconnectAttachmentRequest(proto.Message): + r"""A request message for InterconnectAttachments.SetLabels. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Project ID for this request. + region (str): + The region for this request. + region_set_labels_request_resource (google.cloud.compute_v1.types.RegionSetLabelsRequest): + The body resource for this request + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + resource (str): + Name or id of the resource for this request. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + region_set_labels_request_resource: "RegionSetLabelsRequest" = proto.Field( + proto.MESSAGE, + number=259357782, + message="RegionSetLabelsRequest", + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class SetLabelsInterconnectRequest(proto.Message): + r"""A request message for Interconnects.SetLabels. See the method description for details. Attributes: @@ -88785,71 +91203,11 @@ class SetLabelsImageRequest(proto.Message): ) -class SetLabelsInstanceRequest(proto.Message): - r"""A request message for Instances.SetLabels. See the method +class SetLabelsRegionDiskRequest(proto.Message): + r"""A request message for RegionDisks.SetLabels. See the method description for details. - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - instance (str): - Name of the instance scoping this request. - instances_set_labels_request_resource (google.cloud.compute_v1.types.InstancesSetLabelsRequest): - The body resource for this request - project (str): - Project ID for this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. For example, consider a situation - where you make an initial request and the - request times out. If you make the request again - with the same request ID, the server can check - if original operation with the same request ID - was received, and if so, will ignore the second - request. This prevents clients from accidentally - creating duplicate commitments. The request ID - must be a valid UUID with the exception that - zero UUID is not supported ( - 00000000-0000-0000-0000-000000000000). - - This field is a member of `oneof`_ ``_request_id``. - zone (str): - The name of the zone for this request. - """ - - instance: str = proto.Field( - proto.STRING, - number=18257045, - ) - instances_set_labels_request_resource: "InstancesSetLabelsRequest" = proto.Field( - proto.MESSAGE, - number=207749344, - message="InstancesSetLabelsRequest", - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, - optional=True, - ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) - - -class SetLabelsInterconnectAttachmentRequest(proto.Message): - r"""A request message for InterconnectAttachments.SetLabels. See - the method description for details. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: @@ -88905,37 +91263,9 @@ class SetLabelsInterconnectAttachmentRequest(proto.Message): ) -class SetLabelsInterconnectRequest(proto.Message): - r"""A request message for Interconnects.SetLabels. See the method - description for details. - - Attributes: - global_set_labels_request_resource (google.cloud.compute_v1.types.GlobalSetLabelsRequest): - The body resource for this request - project (str): - Project ID for this request. - resource (str): - Name or id of the resource for this request. - """ - - global_set_labels_request_resource: "GlobalSetLabelsRequest" = proto.Field( - proto.MESSAGE, - number=319917189, - message="GlobalSetLabelsRequest", - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - resource: str = proto.Field( - proto.STRING, - number=195806222, - ) - - -class SetLabelsRegionDiskRequest(proto.Message): - r"""A request message for RegionDisks.SetLabels. See the method - description for details. +class SetLabelsRegionInstantSnapshotRequest(proto.Message): + r"""A request message for RegionInstantSnapshots.SetLabels. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -91844,6 +94174,32 @@ class Snapshot(proto.Message): of a given disk name. This field is a member of `oneof`_ ``_source_disk_id``. + source_instant_snapshot (str): + The source instant snapshot used to create + this snapshot. You can provide this as a partial + or full URL to the resource. For example, the + following are valid values: - + https://www.googleapis.com/compute/v1/projects/project/zones/zone + /instantSnapshots/instantSnapshot - + projects/project/zones/zone/instantSnapshots/instantSnapshot + - zones/zone/instantSnapshots/instantSnapshot + + This field is a member of `oneof`_ ``_source_instant_snapshot``. + source_instant_snapshot_encryption_key (google.cloud.compute_v1.types.CustomerEncryptionKey): + Customer provided encryption key when + creating Snapshot from Instant Snapshot. + + This field is a member of `oneof`_ ``_source_instant_snapshot_encryption_key``. + source_instant_snapshot_id (str): + [Output Only] The unique ID of the instant snapshot used to + create this snapshot. This value identifies the exact + instant snapshot that was used to create this persistent + disk. For example, if you created the persistent disk from + an instant snapshot that was later deleted and recreated + under the same name, the source instant snapshot ID would + identify the exact instant snapshot that was used. + + This field is a member of `oneof`_ ``_source_instant_snapshot_id``. source_snapshot_schedule_policy (str): [Output Only] URL of the resource policy which created this scheduled snapshot. @@ -92099,6 +94455,22 @@ class StorageBytesStatus(proto.Enum): number=454190809, optional=True, ) + source_instant_snapshot: str = proto.Field( + proto.STRING, + number=219202054, + optional=True, + ) + source_instant_snapshot_encryption_key: "CustomerEncryptionKey" = proto.Field( + proto.MESSAGE, + number=436536060, + optional=True, + message="CustomerEncryptionKey", + ) + source_instant_snapshot_id: str = proto.Field( + proto.STRING, + number=287582708, + optional=True, + ) source_snapshot_schedule_policy: str = proto.Field( proto.STRING, number=235756291, @@ -98931,6 +101303,40 @@ class TestIamPermissionsInstanceTemplateRequest(proto.Message): ) +class TestIamPermissionsInstantSnapshotRequest(proto.Message): + r"""A request message for InstantSnapshots.TestIamPermissions. + See the method description for details. + + Attributes: + project (str): + Project ID for this request. + resource (str): + Name or id of the resource for this request. + test_permissions_request_resource (google.cloud.compute_v1.types.TestPermissionsRequest): + The body resource for this request + zone (str): + The name of the zone for this request. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + test_permissions_request_resource: "TestPermissionsRequest" = proto.Field( + proto.MESSAGE, + number=439214758, + message="TestPermissionsRequest", + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + class TestIamPermissionsLicenseCodeRequest(proto.Message): r"""A request message for LicenseCodes.TestIamPermissions. See the method description for details. @@ -99284,6 +101690,41 @@ class TestIamPermissionsRegionDiskRequest(proto.Message): ) +class TestIamPermissionsRegionInstantSnapshotRequest(proto.Message): + r"""A request message for + RegionInstantSnapshots.TestIamPermissions. See the method + description for details. + + Attributes: + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + resource (str): + Name or id of the resource for this request. + test_permissions_request_resource (google.cloud.compute_v1.types.TestPermissionsRequest): + The body resource for this request + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + test_permissions_request_resource: "TestPermissionsRequest" = proto.Field( + proto.MESSAGE, + number=439214758, + message="TestPermissionsRequest", + ) + + class TestIamPermissionsRegionNetworkFirewallPolicyRequest(proto.Message): r"""A request message for RegionNetworkFirewallPolicies.TestIamPermissions. See the method @@ -102679,6 +105120,13 @@ class VpnGateway(proto.Message): resource. This field is a member of `oneof`_ ``_description``. + gateway_ip_version (str): + The IP family of the gateway IPs for the + HA-VPN gateway interfaces. If not specified, + IPV4 will be used. Check the GatewayIpVersion + enum for the list of possible values. + + This field is a member of `oneof`_ ``_gateway_ip_version``. id (int): [Output Only] The unique identifier for the resource. This identifier is defined by the server. @@ -102746,6 +105194,25 @@ class VpnGateway(proto.Message): this VPN gateway. """ + class GatewayIpVersion(proto.Enum): + r"""The IP family of the gateway IPs for the HA-VPN gateway + interfaces. If not specified, IPV4 will be used. + + Values: + UNDEFINED_GATEWAY_IP_VERSION (0): + A value indicating that the enum field is not + set. + IPV4 (2254341): + Every HA-VPN gateway interface is configured + with an IPv4 address. + IPV6 (2254343): + Every HA-VPN gateway interface is configured + with an IPv6 address. + """ + UNDEFINED_GATEWAY_IP_VERSION = 0 + IPV4 = 2254341 + IPV6 = 2254343 + class StackType(proto.Enum): r"""The stack type for this VPN gateway to identify the IP protocols that are enabled. Possible values are: IPV4_ONLY, IPV4_IPV6. If not @@ -102775,6 +105242,11 @@ class StackType(proto.Enum): number=422937596, optional=True, ) + gateway_ip_version: str = proto.Field( + proto.STRING, + number=65074843, + optional=True, + ) id: int = proto.Field( proto.UINT64, number=3355, @@ -103211,6 +105683,13 @@ class VpnGatewayVpnGatewayInterface(proto.Message): regional external IP address. This field is a member of `oneof`_ ``_ip_address``. + ipv6_address (str): + [Output Only] IPv6 address for this VPN interface associated + with the VPN gateway. The IPv6 address must be a regional + external IPv6 address. The format is RFC 5952 format (e.g. + 2001:db8::2d9:51:0:0). + + This field is a member of `oneof`_ ``_ipv6_address``. """ id: int = proto.Field( @@ -103228,6 +105707,11 @@ class VpnGatewayVpnGatewayInterface(proto.Message): number=406272220, optional=True, ) + ipv6_address: str = proto.Field( + proto.STRING, + number=341563804, + optional=True, + ) class VpnGatewaysGetStatusResponse(proto.Message): diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_aggregated_list_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_aggregated_list_sync.py new file mode 100644 index 000000000000..073027fa297e --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_aggregated_list_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AggregatedList +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_InstantSnapshots_AggregatedList_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_aggregated_list(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.AggregatedListInstantSnapshotsRequest( + project="project_value", + ) + + # Make the request + page_result = client.aggregated_list(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END compute_v1_generated_InstantSnapshots_AggregatedList_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_delete_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_delete_sync.py new file mode 100644 index 000000000000..0fbf0ad239e9 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_delete_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Delete +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_InstantSnapshots_Delete_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_delete(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.DeleteInstantSnapshotRequest( + instant_snapshot="instant_snapshot_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_InstantSnapshots_Delete_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_get_iam_policy_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_get_iam_policy_sync.py new file mode 100644 index 000000000000..b9ef0c3e988b --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_get_iam_policy_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_InstantSnapshots_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_get_iam_policy(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.GetIamPolicyInstantSnapshotRequest( + project="project_value", + resource="resource_value", + zone="zone_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_InstantSnapshots_GetIamPolicy_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_get_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_get_sync.py new file mode 100644 index 000000000000..bf4d6c377b86 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_get_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Get +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_InstantSnapshots_Get_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_get(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.GetInstantSnapshotRequest( + instant_snapshot="instant_snapshot_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_InstantSnapshots_Get_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_insert_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_insert_sync.py new file mode 100644 index 000000000000..c5fdf026eae5 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_insert_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Insert +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_InstantSnapshots_Insert_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_insert(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.InsertInstantSnapshotRequest( + project="project_value", + zone="zone_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_InstantSnapshots_Insert_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_list_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_list_sync.py new file mode 100644 index 000000000000..5a3795581611 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_list_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for List +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_InstantSnapshots_List_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_list(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.ListInstantSnapshotsRequest( + project="project_value", + zone="zone_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END compute_v1_generated_InstantSnapshots_List_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_set_iam_policy_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_set_iam_policy_sync.py new file mode 100644 index 000000000000..2db69872943b --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_set_iam_policy_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_InstantSnapshots_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_set_iam_policy(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.SetIamPolicyInstantSnapshotRequest( + project="project_value", + resource="resource_value", + zone="zone_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_InstantSnapshots_SetIamPolicy_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_set_labels_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_set_labels_sync.py new file mode 100644 index 000000000000..cdb1e4d76d4a --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_set_labels_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 SetLabels +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_InstantSnapshots_SetLabels_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_set_labels(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.SetLabelsInstantSnapshotRequest( + project="project_value", + resource="resource_value", + zone="zone_value", + ) + + # Make the request + response = client.set_labels(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_InstantSnapshots_SetLabels_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_test_iam_permissions_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_test_iam_permissions_sync.py new file mode 100644 index 000000000000..5bd9b59cc6dd --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instant_snapshots_test_iam_permissions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_InstantSnapshots_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_test_iam_permissions(): + # Create a client + client = compute_v1.InstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.TestIamPermissionsInstantSnapshotRequest( + project="project_value", + resource="resource_value", + zone="zone_value", + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_InstantSnapshots_TestIamPermissions_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_projects_set_cloud_armor_tier_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_projects_set_cloud_armor_tier_sync.py new file mode 100644 index 000000000000..fe6da35b3d0f --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_projects_set_cloud_armor_tier_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 SetCloudArmorTier +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_Projects_SetCloudArmorTier_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_set_cloud_armor_tier(): + # Create a client + client = compute_v1.ProjectsClient() + + # Initialize request argument(s) + request = compute_v1.SetCloudArmorTierProjectRequest( + project="project_value", + ) + + # Make the request + response = client.set_cloud_armor_tier(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_Projects_SetCloudArmorTier_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_delete_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_delete_sync.py new file mode 100644 index 000000000000..9787dda15315 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_delete_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Delete +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_RegionInstantSnapshots_Delete_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_delete(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.DeleteRegionInstantSnapshotRequest( + instant_snapshot="instant_snapshot_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_RegionInstantSnapshots_Delete_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_get_iam_policy_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_get_iam_policy_sync.py new file mode 100644 index 000000000000..64df66d6f11f --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_get_iam_policy_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_RegionInstantSnapshots_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_get_iam_policy(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.GetIamPolicyRegionInstantSnapshotRequest( + project="project_value", + region="region_value", + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_RegionInstantSnapshots_GetIamPolicy_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_get_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_get_sync.py new file mode 100644 index 000000000000..560d1fcade8d --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_get_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Get +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_RegionInstantSnapshots_Get_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_get(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.GetRegionInstantSnapshotRequest( + instant_snapshot="instant_snapshot_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_RegionInstantSnapshots_Get_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_insert_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_insert_sync.py new file mode 100644 index 000000000000..ecf7009989f7 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_insert_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Insert +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_RegionInstantSnapshots_Insert_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_insert(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.InsertRegionInstantSnapshotRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_RegionInstantSnapshots_Insert_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_list_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_list_sync.py new file mode 100644 index 000000000000..822242b41402 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_list_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for List +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_RegionInstantSnapshots_List_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_list(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.ListRegionInstantSnapshotsRequest( + project="project_value", + region="region_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END compute_v1_generated_RegionInstantSnapshots_List_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_set_iam_policy_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_set_iam_policy_sync.py new file mode 100644 index 000000000000..b6d980346d7e --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_set_iam_policy_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_RegionInstantSnapshots_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_set_iam_policy(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.SetIamPolicyRegionInstantSnapshotRequest( + project="project_value", + region="region_value", + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_RegionInstantSnapshots_SetIamPolicy_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_set_labels_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_set_labels_sync.py new file mode 100644 index 000000000000..5dacc2bac29c --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_set_labels_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 SetLabels +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_RegionInstantSnapshots_SetLabels_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_set_labels(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.SetLabelsRegionInstantSnapshotRequest( + project="project_value", + region="region_value", + resource="resource_value", + ) + + # Make the request + response = client.set_labels(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_RegionInstantSnapshots_SetLabels_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_test_iam_permissions_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_test_iam_permissions_sync.py new file mode 100644 index 000000000000..60dfe07333bb --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_region_instant_snapshots_test_iam_permissions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_RegionInstantSnapshots_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_test_iam_permissions(): + # Create a client + client = compute_v1.RegionInstantSnapshotsClient() + + # Initialize request argument(s) + request = compute_v1.TestIamPermissionsRegionInstantSnapshotRequest( + project="project_value", + region="region_value", + resource="resource_value", + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_RegionInstantSnapshots_TestIamPermissions_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json b/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json index 9b1c11b50594..4573426b0d99 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.17.0" + "version": "1.18.0" }, "snippets": [ { @@ -20911,22 +20911,22 @@ "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient", - "shortName": "InterconnectAttachmentsClient" + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient", + "shortName": "InstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient.aggregated_list", + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1.InterconnectAttachments.AggregatedList", + "fullName": "google.cloud.compute.v1.InstantSnapshots.AggregatedList", "service": { - "fullName": "google.cloud.compute.v1.InterconnectAttachments", - "shortName": "InterconnectAttachments" + "fullName": "google.cloud.compute.v1.InstantSnapshots", + "shortName": "InstantSnapshots" }, "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AggregatedListInterconnectAttachmentsRequest" + "type": "google.cloud.compute_v1.types.AggregatedListInstantSnapshotsRequest" }, { "name": "project", @@ -20945,14 +20945,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.interconnect_attachments.pagers.AggregatedListPager", + "resultType": "google.cloud.compute_v1.services.instant_snapshots.pagers.AggregatedListPager", "shortName": "aggregated_list" }, "description": "Sample for AggregatedList", - "file": "compute_v1_generated_interconnect_attachments_aggregated_list_sync.py", + "file": "compute_v1_generated_instant_snapshots_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_InterconnectAttachments_AggregatedList_sync", + "regionTag": "compute_v1_generated_InstantSnapshots_AggregatedList_sync", "segments": [ { "end": 52, @@ -20985,39 +20985,39 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnect_attachments_aggregated_list_sync.py" + "title": "compute_v1_generated_instant_snapshots_aggregated_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient", - "shortName": "InterconnectAttachmentsClient" + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient", + "shortName": "InstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient.delete", + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient.delete", "method": { - "fullName": "google.cloud.compute.v1.InterconnectAttachments.Delete", + "fullName": "google.cloud.compute.v1.InstantSnapshots.Delete", "service": { - "fullName": "google.cloud.compute.v1.InterconnectAttachments", - "shortName": "InterconnectAttachments" + "fullName": "google.cloud.compute.v1.InstantSnapshots", + "shortName": "InstantSnapshots" }, "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteInterconnectAttachmentRequest" + "type": "google.cloud.compute_v1.types.DeleteInstantSnapshotRequest" }, { "name": "project", "type": "str" }, { - "name": "region", + "name": "zone", "type": "str" }, { - "name": "interconnect_attachment", + "name": "instant_snapshot", "type": "str" }, { @@ -21037,10 +21037,10 @@ "shortName": "delete" }, "description": "Sample for Delete", - "file": "compute_v1_generated_interconnect_attachments_delete_sync.py", + "file": "compute_v1_generated_instant_snapshots_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_InterconnectAttachments_Delete_sync", + "regionTag": "compute_v1_generated_InstantSnapshots_Delete_sync", "segments": [ { "end": 53, @@ -21073,39 +21073,39 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnect_attachments_delete_sync.py" + "title": "compute_v1_generated_instant_snapshots_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient", - "shortName": "InterconnectAttachmentsClient" + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient", + "shortName": "InstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient.get", + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient.get_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.InterconnectAttachments.Get", + "fullName": "google.cloud.compute.v1.InstantSnapshots.GetIamPolicy", "service": { - "fullName": "google.cloud.compute.v1.InterconnectAttachments", - "shortName": "InterconnectAttachments" + "fullName": "google.cloud.compute.v1.InstantSnapshots", + "shortName": "InstantSnapshots" }, - "shortName": "Get" + "shortName": "GetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetInterconnectAttachmentRequest" + "type": "google.cloud.compute_v1.types.GetIamPolicyInstantSnapshotRequest" }, { "name": "project", "type": "str" }, { - "name": "region", + "name": "zone", "type": "str" }, { - "name": "interconnect_attachment", + "name": "resource", "type": "str" }, { @@ -21121,14 +21121,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.InterconnectAttachment", - "shortName": "get" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "get_iam_policy" }, - "description": "Sample for Get", - "file": "compute_v1_generated_interconnect_attachments_get_sync.py", + "description": "Sample for GetIamPolicy", + "file": "compute_v1_generated_instant_snapshots_get_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_InterconnectAttachments_Get_sync", + "regionTag": "compute_v1_generated_InstantSnapshots_GetIamPolicy_sync", "segments": [ { "end": 53, @@ -21161,40 +21161,40 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnect_attachments_get_sync.py" + "title": "compute_v1_generated_instant_snapshots_get_iam_policy_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient", - "shortName": "InterconnectAttachmentsClient" + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient", + "shortName": "InstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient.insert", + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient.get", "method": { - "fullName": "google.cloud.compute.v1.InterconnectAttachments.Insert", + "fullName": "google.cloud.compute.v1.InstantSnapshots.Get", "service": { - "fullName": "google.cloud.compute.v1.InterconnectAttachments", - "shortName": "InterconnectAttachments" + "fullName": "google.cloud.compute.v1.InstantSnapshots", + "shortName": "InstantSnapshots" }, - "shortName": "Insert" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertInterconnectAttachmentRequest" + "type": "google.cloud.compute_v1.types.GetInstantSnapshotRequest" }, { "name": "project", "type": "str" }, { - "name": "region", + "name": "zone", "type": "str" }, { - "name": "interconnect_attachment_resource", - "type": "google.cloud.compute_v1.types.InterconnectAttachment" + "name": "instant_snapshot", + "type": "str" }, { "name": "retry", @@ -21209,22 +21209,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "resultType": "google.cloud.compute_v1.types.InstantSnapshot", + "shortName": "get" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_interconnect_attachments_insert_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_instant_snapshots_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_InterconnectAttachments_Insert_sync", + "regionTag": "compute_v1_generated_InstantSnapshots_Get_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -21234,52 +21234,56 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnect_attachments_insert_sync.py" + "title": "compute_v1_generated_instant_snapshots_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient", - "shortName": "InterconnectAttachmentsClient" + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient", + "shortName": "InstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient.list", + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient.insert", "method": { - "fullName": "google.cloud.compute.v1.InterconnectAttachments.List", + "fullName": "google.cloud.compute.v1.InstantSnapshots.Insert", "service": { - "fullName": "google.cloud.compute.v1.InterconnectAttachments", - "shortName": "InterconnectAttachments" + "fullName": "google.cloud.compute.v1.InstantSnapshots", + "shortName": "InstantSnapshots" }, - "shortName": "List" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListInterconnectAttachmentsRequest" + "type": "google.cloud.compute_v1.types.InsertInstantSnapshotRequest" }, { "name": "project", "type": "str" }, { - "name": "region", + "name": "zone", "type": "str" }, + { + "name": "instant_snapshot_resource", + "type": "google.cloud.compute_v1.types.InstantSnapshot" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -21293,22 +21297,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.interconnect_attachments.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" }, - "description": "Sample for List", - "file": "compute_v1_generated_interconnect_attachments_list_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_instant_snapshots_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_InterconnectAttachments_List_sync", + "regionTag": "compute_v1_generated_InstantSnapshots_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -21328,50 +21332,42 @@ "type": "REQUEST_EXECUTION" }, { - "end": 54, + "end": 53, "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnect_attachments_list_sync.py" + "title": "compute_v1_generated_instant_snapshots_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient", - "shortName": "InterconnectAttachmentsClient" + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient", + "shortName": "InstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient.patch", + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient.list", "method": { - "fullName": "google.cloud.compute.v1.InterconnectAttachments.Patch", + "fullName": "google.cloud.compute.v1.InstantSnapshots.List", "service": { - "fullName": "google.cloud.compute.v1.InterconnectAttachments", - "shortName": "InterconnectAttachments" + "fullName": "google.cloud.compute.v1.InstantSnapshots", + "shortName": "InstantSnapshots" }, - "shortName": "Patch" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchInterconnectAttachmentRequest" + "type": "google.cloud.compute_v1.types.ListInstantSnapshotsRequest" }, { "name": "project", "type": "str" }, { - "name": "region", - "type": "str" - }, - { - "name": "interconnect_attachment", + "name": "zone", "type": "str" }, - { - "name": "interconnect_attachment_resource", - "type": "google.cloud.compute_v1.types.InterconnectAttachment" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -21385,14 +21381,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "resultType": "google.cloud.compute_v1.services.instant_snapshots.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_interconnect_attachments_patch_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_instant_snapshots_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_InterconnectAttachments_Patch_sync", + "regionTag": "compute_v1_generated_InstantSnapshots_List_sync", "segments": [ { "end": 53, @@ -21410,50 +21406,50 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 51, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnect_attachments_patch_sync.py" + "title": "compute_v1_generated_instant_snapshots_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient", - "shortName": "InterconnectAttachmentsClient" + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient", + "shortName": "InstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient.set_labels", + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient.set_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.InterconnectAttachments.SetLabels", + "fullName": "google.cloud.compute.v1.InstantSnapshots.SetIamPolicy", "service": { - "fullName": "google.cloud.compute.v1.InterconnectAttachments", - "shortName": "InterconnectAttachments" + "fullName": "google.cloud.compute.v1.InstantSnapshots", + "shortName": "InstantSnapshots" }, - "shortName": "SetLabels" + "shortName": "SetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetLabelsInterconnectAttachmentRequest" + "type": "google.cloud.compute_v1.types.SetIamPolicyInstantSnapshotRequest" }, { "name": "project", "type": "str" }, { - "name": "region", + "name": "zone", "type": "str" }, { @@ -21461,8 +21457,8 @@ "type": "str" }, { - "name": "region_set_labels_request_resource", - "type": "google.cloud.compute_v1.types.RegionSetLabelsRequest" + "name": "zone_set_policy_request_resource", + "type": "google.cloud.compute_v1.types.ZoneSetPolicyRequest" }, { "name": "retry", @@ -21477,14 +21473,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_labels" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "set_iam_policy" }, - "description": "Sample for SetLabels", - "file": "compute_v1_generated_interconnect_attachments_set_labels_sync.py", + "description": "Sample for SetIamPolicy", + "file": "compute_v1_generated_instant_snapshots_set_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_InterconnectAttachments_SetLabels_sync", + "regionTag": "compute_v1_generated_InstantSnapshots_SetIamPolicy_sync", "segments": [ { "end": 53, @@ -21517,116 +21513,44 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnect_attachments_set_labels_sync.py" + "title": "compute_v1_generated_instant_snapshots_set_iam_policy_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectLocationsClient", - "shortName": "InterconnectLocationsClient" + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient", + "shortName": "InstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectLocationsClient.get", + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient.set_labels", "method": { - "fullName": "google.cloud.compute.v1.InterconnectLocations.Get", + "fullName": "google.cloud.compute.v1.InstantSnapshots.SetLabels", "service": { - "fullName": "google.cloud.compute.v1.InterconnectLocations", - "shortName": "InterconnectLocations" + "fullName": "google.cloud.compute.v1.InstantSnapshots", + "shortName": "InstantSnapshots" }, - "shortName": "Get" + "shortName": "SetLabels" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetInterconnectLocationRequest" + "type": "google.cloud.compute_v1.types.SetLabelsInstantSnapshotRequest" }, { "name": "project", "type": "str" }, { - "name": "interconnect_location", + "name": "zone", "type": "str" }, { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.compute_v1.types.InterconnectLocation", - "shortName": "get" - }, - "description": "Sample for Get", - "file": "compute_v1_generated_interconnect_locations_get_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_InterconnectLocations_Get_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "compute_v1_generated_interconnect_locations_get_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.compute_v1.InterconnectLocationsClient", - "shortName": "InterconnectLocationsClient" - }, - "fullName": "google.cloud.compute_v1.InterconnectLocationsClient.list", - "method": { - "fullName": "google.cloud.compute.v1.InterconnectLocations.List", - "service": { - "fullName": "google.cloud.compute.v1.InterconnectLocations", - "shortName": "InterconnectLocations" - }, - "shortName": "List" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.compute_v1.types.ListInterconnectLocationsRequest" + "name": "resource", + "type": "str" }, { - "name": "project", - "type": "str" + "name": "zone_set_labels_request_resource", + "type": "google.cloud.compute_v1.types.ZoneSetLabelsRequest" }, { "name": "retry", @@ -21641,22 +21565,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.interconnect_locations.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "set_labels" }, - "description": "Sample for List", - "file": "compute_v1_generated_interconnect_locations_list_sync.py", + "description": "Sample for SetLabels", + "file": "compute_v1_generated_instant_snapshots_set_labels_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_InterconnectLocations_List_sync", + "regionTag": "compute_v1_generated_InstantSnapshots_SetLabels_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -21666,52 +21590,60 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnect_locations_list_sync.py" + "title": "compute_v1_generated_instant_snapshots_set_labels_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectRemoteLocationsClient", - "shortName": "InterconnectRemoteLocationsClient" + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient", + "shortName": "InstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectRemoteLocationsClient.get", + "fullName": "google.cloud.compute_v1.InstantSnapshotsClient.test_iam_permissions", "method": { - "fullName": "google.cloud.compute.v1.InterconnectRemoteLocations.Get", + "fullName": "google.cloud.compute.v1.InstantSnapshots.TestIamPermissions", "service": { - "fullName": "google.cloud.compute.v1.InterconnectRemoteLocations", - "shortName": "InterconnectRemoteLocations" + "fullName": "google.cloud.compute.v1.InstantSnapshots", + "shortName": "InstantSnapshots" }, - "shortName": "Get" + "shortName": "TestIamPermissions" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetInterconnectRemoteLocationRequest" + "type": "google.cloud.compute_v1.types.TestIamPermissionsInstantSnapshotRequest" }, { "name": "project", "type": "str" }, { - "name": "interconnect_remote_location", + "name": "zone", + "type": "str" + }, + { + "name": "resource", "type": "str" }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -21725,22 +21657,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.InterconnectRemoteLocation", - "shortName": "get" + "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" }, - "description": "Sample for Get", - "file": "compute_v1_generated_interconnect_remote_locations_get_sync.py", + "description": "Sample for TestIamPermissions", + "file": "compute_v1_generated_instant_snapshots_test_iam_permissions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_InterconnectRemoteLocations_Get_sync", + "regionTag": "compute_v1_generated_InstantSnapshots_TestIamPermissions_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -21750,43 +21682,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnect_remote_locations_get_sync.py" + "title": "compute_v1_generated_instant_snapshots_test_iam_permissions_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectRemoteLocationsClient", - "shortName": "InterconnectRemoteLocationsClient" + "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient", + "shortName": "InterconnectAttachmentsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectRemoteLocationsClient.list", + "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1.InterconnectRemoteLocations.List", + "fullName": "google.cloud.compute.v1.InterconnectAttachments.AggregatedList", "service": { - "fullName": "google.cloud.compute.v1.InterconnectRemoteLocations", - "shortName": "InterconnectRemoteLocations" + "fullName": "google.cloud.compute.v1.InterconnectAttachments", + "shortName": "InterconnectAttachments" }, - "shortName": "List" + "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListInterconnectRemoteLocationsRequest" + "type": "google.cloud.compute_v1.types.AggregatedListInterconnectAttachmentsRequest" }, { "name": "project", @@ -21805,14 +21737,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.interconnect_remote_locations.pagers.ListPager", - "shortName": "list" + "resultType": "google.cloud.compute_v1.services.interconnect_attachments.pagers.AggregatedListPager", + "shortName": "aggregated_list" }, - "description": "Sample for List", - "file": "compute_v1_generated_interconnect_remote_locations_list_sync.py", + "description": "Sample for AggregatedList", + "file": "compute_v1_generated_interconnect_attachments_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_InterconnectRemoteLocations_List_sync", + "regionTag": "compute_v1_generated_InterconnectAttachments_AggregatedList_sync", "segments": [ { "end": 52, @@ -21845,35 +21777,39 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnect_remote_locations_list_sync.py" + "title": "compute_v1_generated_interconnect_attachments_aggregated_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectsClient", - "shortName": "InterconnectsClient" + "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient", + "shortName": "InterconnectAttachmentsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectsClient.delete", + "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient.delete", "method": { - "fullName": "google.cloud.compute.v1.Interconnects.Delete", + "fullName": "google.cloud.compute.v1.InterconnectAttachments.Delete", "service": { - "fullName": "google.cloud.compute.v1.Interconnects", - "shortName": "Interconnects" + "fullName": "google.cloud.compute.v1.InterconnectAttachments", + "shortName": "InterconnectAttachments" }, "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteInterconnectRequest" + "type": "google.cloud.compute_v1.types.DeleteInterconnectAttachmentRequest" }, { "name": "project", "type": "str" }, { - "name": "interconnect", + "name": "region", + "type": "str" + }, + { + "name": "interconnect_attachment", "type": "str" }, { @@ -21893,18 +21829,18 @@ "shortName": "delete" }, "description": "Sample for Delete", - "file": "compute_v1_generated_interconnects_delete_sync.py", + "file": "compute_v1_generated_interconnect_attachments_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Interconnects_Delete_sync", + "regionTag": "compute_v1_generated_InterconnectAttachments_Delete_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -21914,50 +21850,54 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnects_delete_sync.py" + "title": "compute_v1_generated_interconnect_attachments_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectsClient", - "shortName": "InterconnectsClient" + "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient", + "shortName": "InterconnectAttachmentsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectsClient.get_diagnostics", + "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient.get", "method": { - "fullName": "google.cloud.compute.v1.Interconnects.GetDiagnostics", + "fullName": "google.cloud.compute.v1.InterconnectAttachments.Get", "service": { - "fullName": "google.cloud.compute.v1.Interconnects", - "shortName": "Interconnects" + "fullName": "google.cloud.compute.v1.InterconnectAttachments", + "shortName": "InterconnectAttachments" }, - "shortName": "GetDiagnostics" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetDiagnosticsInterconnectRequest" + "type": "google.cloud.compute_v1.types.GetInterconnectAttachmentRequest" }, { "name": "project", "type": "str" }, { - "name": "interconnect", + "name": "region", + "type": "str" + }, + { + "name": "interconnect_attachment", "type": "str" }, { @@ -21973,22 +21913,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.InterconnectsGetDiagnosticsResponse", - "shortName": "get_diagnostics" + "resultType": "google.cloud.compute_v1.types.InterconnectAttachment", + "shortName": "get" }, - "description": "Sample for GetDiagnostics", - "file": "compute_v1_generated_interconnects_get_diagnostics_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_interconnect_attachments_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Interconnects_GetDiagnostics_sync", + "regionTag": "compute_v1_generated_InterconnectAttachments_Get_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -21998,52 +21938,56 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnects_get_diagnostics_sync.py" + "title": "compute_v1_generated_interconnect_attachments_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectsClient", - "shortName": "InterconnectsClient" + "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient", + "shortName": "InterconnectAttachmentsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectsClient.get_macsec_config", + "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient.insert", "method": { - "fullName": "google.cloud.compute.v1.Interconnects.GetMacsecConfig", + "fullName": "google.cloud.compute.v1.InterconnectAttachments.Insert", "service": { - "fullName": "google.cloud.compute.v1.Interconnects", - "shortName": "Interconnects" + "fullName": "google.cloud.compute.v1.InterconnectAttachments", + "shortName": "InterconnectAttachments" }, - "shortName": "GetMacsecConfig" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetMacsecConfigInterconnectRequest" + "type": "google.cloud.compute_v1.types.InsertInterconnectAttachmentRequest" }, { "name": "project", "type": "str" }, { - "name": "interconnect", + "name": "region", "type": "str" }, + { + "name": "interconnect_attachment_resource", + "type": "google.cloud.compute_v1.types.InterconnectAttachment" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -22057,14 +22001,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.InterconnectsGetMacsecConfigResponse", - "shortName": "get_macsec_config" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" }, - "description": "Sample for GetMacsecConfig", - "file": "compute_v1_generated_interconnects_get_macsec_config_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_interconnect_attachments_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Interconnects_GetMacsecConfig_sync", + "regionTag": "compute_v1_generated_InterconnectAttachments_Insert_sync", "segments": [ { "end": 52, @@ -22097,35 +22041,35 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnects_get_macsec_config_sync.py" + "title": "compute_v1_generated_interconnect_attachments_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectsClient", - "shortName": "InterconnectsClient" + "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient", + "shortName": "InterconnectAttachmentsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectsClient.get", + "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient.list", "method": { - "fullName": "google.cloud.compute.v1.Interconnects.Get", + "fullName": "google.cloud.compute.v1.InterconnectAttachments.List", "service": { - "fullName": "google.cloud.compute.v1.Interconnects", - "shortName": "Interconnects" + "fullName": "google.cloud.compute.v1.InterconnectAttachments", + "shortName": "InterconnectAttachments" }, - "shortName": "Get" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetInterconnectRequest" + "type": "google.cloud.compute_v1.types.ListInterconnectAttachmentsRequest" }, { "name": "project", "type": "str" }, { - "name": "interconnect", + "name": "region", "type": "str" }, { @@ -22141,22 +22085,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Interconnect", - "shortName": "get" + "resultType": "google.cloud.compute_v1.services.interconnect_attachments.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Get", - "file": "compute_v1_generated_interconnects_get_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_interconnect_attachments_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Interconnects_Get_sync", + "regionTag": "compute_v1_generated_InterconnectAttachments_List_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -22176,41 +22120,49 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 54, "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnects_get_sync.py" + "title": "compute_v1_generated_interconnect_attachments_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectsClient", - "shortName": "InterconnectsClient" + "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient", + "shortName": "InterconnectAttachmentsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectsClient.insert", + "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient.patch", "method": { - "fullName": "google.cloud.compute.v1.Interconnects.Insert", + "fullName": "google.cloud.compute.v1.InterconnectAttachments.Patch", "service": { - "fullName": "google.cloud.compute.v1.Interconnects", - "shortName": "Interconnects" + "fullName": "google.cloud.compute.v1.InterconnectAttachments", + "shortName": "InterconnectAttachments" }, - "shortName": "Insert" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertInterconnectRequest" + "type": "google.cloud.compute_v1.types.PatchInterconnectAttachmentRequest" }, { "name": "project", "type": "str" }, { - "name": "interconnect_resource", - "type": "google.cloud.compute_v1.types.Interconnect" + "name": "region", + "type": "str" + }, + { + "name": "interconnect_attachment", + "type": "str" + }, + { + "name": "interconnect_attachment_resource", + "type": "google.cloud.compute_v1.types.InterconnectAttachment" }, { "name": "retry", @@ -22226,21 +22178,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "shortName": "patch" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_interconnects_insert_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_interconnect_attachments_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Interconnects_Insert_sync", + "regionTag": "compute_v1_generated_InterconnectAttachments_Patch_sync", "segments": [ { - "end": 51, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 53, "start": 27, "type": "SHORT" }, @@ -22250,48 +22202,60 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnects_insert_sync.py" + "title": "compute_v1_generated_interconnect_attachments_patch_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectsClient", - "shortName": "InterconnectsClient" + "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient", + "shortName": "InterconnectAttachmentsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectsClient.list", + "fullName": "google.cloud.compute_v1.InterconnectAttachmentsClient.set_labels", "method": { - "fullName": "google.cloud.compute.v1.Interconnects.List", + "fullName": "google.cloud.compute.v1.InterconnectAttachments.SetLabels", "service": { - "fullName": "google.cloud.compute.v1.Interconnects", - "shortName": "Interconnects" + "fullName": "google.cloud.compute.v1.InterconnectAttachments", + "shortName": "InterconnectAttachments" }, - "shortName": "List" + "shortName": "SetLabels" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListInterconnectsRequest" + "type": "google.cloud.compute_v1.types.SetLabelsInterconnectAttachmentRequest" }, { "name": "project", "type": "str" }, + { + "name": "region", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "region_set_labels_request_resource", + "type": "google.cloud.compute_v1.types.RegionSetLabelsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -22305,22 +22269,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.interconnects.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "set_labels" }, - "description": "Sample for List", - "file": "compute_v1_generated_interconnects_list_sync.py", + "description": "Sample for SetLabels", + "file": "compute_v1_generated_interconnect_attachments_set_labels_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Interconnects_List_sync", + "regionTag": "compute_v1_generated_InterconnectAttachments_SetLabels_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -22330,56 +22294,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnects_list_sync.py" + "title": "compute_v1_generated_interconnect_attachments_set_labels_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectsClient", - "shortName": "InterconnectsClient" + "fullName": "google.cloud.compute_v1.InterconnectLocationsClient", + "shortName": "InterconnectLocationsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectsClient.patch", + "fullName": "google.cloud.compute_v1.InterconnectLocationsClient.get", "method": { - "fullName": "google.cloud.compute.v1.Interconnects.Patch", + "fullName": "google.cloud.compute.v1.InterconnectLocations.Get", "service": { - "fullName": "google.cloud.compute.v1.Interconnects", - "shortName": "Interconnects" + "fullName": "google.cloud.compute.v1.InterconnectLocations", + "shortName": "InterconnectLocations" }, - "shortName": "Patch" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchInterconnectRequest" + "type": "google.cloud.compute_v1.types.GetInterconnectLocationRequest" }, { "name": "project", "type": "str" }, { - "name": "interconnect", + "name": "interconnect_location", "type": "str" }, - { - "name": "interconnect_resource", - "type": "google.cloud.compute_v1.types.Interconnect" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -22393,14 +22353,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "resultType": "google.cloud.compute_v1.types.InterconnectLocation", + "shortName": "get" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_interconnects_patch_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_interconnect_locations_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Interconnects_Patch_sync", + "regionTag": "compute_v1_generated_InterconnectLocations_Get_sync", "segments": [ { "end": 52, @@ -22433,41 +22393,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnects_patch_sync.py" + "title": "compute_v1_generated_interconnect_locations_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.InterconnectsClient", - "shortName": "InterconnectsClient" + "fullName": "google.cloud.compute_v1.InterconnectLocationsClient", + "shortName": "InterconnectLocationsClient" }, - "fullName": "google.cloud.compute_v1.InterconnectsClient.set_labels", + "fullName": "google.cloud.compute_v1.InterconnectLocationsClient.list", "method": { - "fullName": "google.cloud.compute.v1.Interconnects.SetLabels", + "fullName": "google.cloud.compute.v1.InterconnectLocations.List", "service": { - "fullName": "google.cloud.compute.v1.Interconnects", - "shortName": "Interconnects" + "fullName": "google.cloud.compute.v1.InterconnectLocations", + "shortName": "InterconnectLocations" }, - "shortName": "SetLabels" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetLabelsInterconnectRequest" + "type": "google.cloud.compute_v1.types.ListInterconnectLocationsRequest" }, { "name": "project", "type": "str" }, - { - "name": "resource", - "type": "str" - }, - { - "name": "global_set_labels_request_resource", - "type": "google.cloud.compute_v1.types.GlobalSetLabelsRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -22481,14 +22433,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_labels" + "resultType": "google.cloud.compute_v1.services.interconnect_locations.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for SetLabels", - "file": "compute_v1_generated_interconnects_set_labels_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_interconnect_locations_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Interconnects_SetLabels_sync", + "regionTag": "compute_v1_generated_InterconnectLocations_List_sync", "segments": [ { "end": 52, @@ -22506,50 +22458,50 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_interconnects_set_labels_sync.py" + "title": "compute_v1_generated_interconnect_locations_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.LicenseCodesClient", - "shortName": "LicenseCodesClient" + "fullName": "google.cloud.compute_v1.InterconnectRemoteLocationsClient", + "shortName": "InterconnectRemoteLocationsClient" }, - "fullName": "google.cloud.compute_v1.LicenseCodesClient.get", + "fullName": "google.cloud.compute_v1.InterconnectRemoteLocationsClient.get", "method": { - "fullName": "google.cloud.compute.v1.LicenseCodes.Get", + "fullName": "google.cloud.compute.v1.InterconnectRemoteLocations.Get", "service": { - "fullName": "google.cloud.compute.v1.LicenseCodes", - "shortName": "LicenseCodes" + "fullName": "google.cloud.compute.v1.InterconnectRemoteLocations", + "shortName": "InterconnectRemoteLocations" }, "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetLicenseCodeRequest" + "type": "google.cloud.compute_v1.types.GetInterconnectRemoteLocationRequest" }, { "name": "project", "type": "str" }, { - "name": "license_code", + "name": "interconnect_remote_location", "type": "str" }, { @@ -22565,14 +22517,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.LicenseCode", + "resultType": "google.cloud.compute_v1.types.InterconnectRemoteLocation", "shortName": "get" }, "description": "Sample for Get", - "file": "compute_v1_generated_license_codes_get_sync.py", + "file": "compute_v1_generated_interconnect_remote_locations_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_LicenseCodes_Get_sync", + "regionTag": "compute_v1_generated_InterconnectRemoteLocations_Get_sync", "segments": [ { "end": 52, @@ -22605,40 +22557,116 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_license_codes_get_sync.py" + "title": "compute_v1_generated_interconnect_remote_locations_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.LicenseCodesClient", - "shortName": "LicenseCodesClient" + "fullName": "google.cloud.compute_v1.InterconnectRemoteLocationsClient", + "shortName": "InterconnectRemoteLocationsClient" }, - "fullName": "google.cloud.compute_v1.LicenseCodesClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1.InterconnectRemoteLocationsClient.list", "method": { - "fullName": "google.cloud.compute.v1.LicenseCodes.TestIamPermissions", + "fullName": "google.cloud.compute.v1.InterconnectRemoteLocations.List", "service": { - "fullName": "google.cloud.compute.v1.LicenseCodes", - "shortName": "LicenseCodes" + "fullName": "google.cloud.compute.v1.InterconnectRemoteLocations", + "shortName": "InterconnectRemoteLocations" }, - "shortName": "TestIamPermissions" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.TestIamPermissionsLicenseCodeRequest" + "type": "google.cloud.compute_v1.types.ListInterconnectRemoteLocationsRequest" }, { "name": "project", "type": "str" }, { - "name": "resource", + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.compute_v1.services.interconnect_remote_locations.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1_generated_interconnect_remote_locations_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_InterconnectRemoteLocations_List_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_interconnect_remote_locations_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.InterconnectsClient", + "shortName": "InterconnectsClient" + }, + "fullName": "google.cloud.compute_v1.InterconnectsClient.delete", + "method": { + "fullName": "google.cloud.compute.v1.Interconnects.Delete", + "service": { + "fullName": "google.cloud.compute.v1.Interconnects", + "shortName": "Interconnects" + }, + "shortName": "Delete" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.DeleteInterconnectRequest" + }, + { + "name": "project", "type": "str" }, { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + "name": "interconnect", + "type": "str" }, { "name": "retry", @@ -22653,14 +22681,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1_generated_license_codes_test_iam_permissions_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_interconnects_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_LicenseCodes_TestIamPermissions_sync", + "regionTag": "compute_v1_generated_Interconnects_Delete_sync", "segments": [ { "end": 52, @@ -22693,35 +22721,35 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_license_codes_test_iam_permissions_sync.py" + "title": "compute_v1_generated_interconnects_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.LicensesClient", - "shortName": "LicensesClient" + "fullName": "google.cloud.compute_v1.InterconnectsClient", + "shortName": "InterconnectsClient" }, - "fullName": "google.cloud.compute_v1.LicensesClient.delete", + "fullName": "google.cloud.compute_v1.InterconnectsClient.get_diagnostics", "method": { - "fullName": "google.cloud.compute.v1.Licenses.Delete", + "fullName": "google.cloud.compute.v1.Interconnects.GetDiagnostics", "service": { - "fullName": "google.cloud.compute.v1.Licenses", - "shortName": "Licenses" + "fullName": "google.cloud.compute.v1.Interconnects", + "shortName": "Interconnects" }, - "shortName": "Delete" + "shortName": "GetDiagnostics" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteLicenseRequest" + "type": "google.cloud.compute_v1.types.GetDiagnosticsInterconnectRequest" }, { "name": "project", "type": "str" }, { - "name": "license_", + "name": "interconnect", "type": "str" }, { @@ -22737,14 +22765,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "resultType": "google.cloud.compute_v1.types.InterconnectsGetDiagnosticsResponse", + "shortName": "get_diagnostics" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_licenses_delete_sync.py", + "description": "Sample for GetDiagnostics", + "file": "compute_v1_generated_interconnects_get_diagnostics_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Licenses_Delete_sync", + "regionTag": "compute_v1_generated_Interconnects_GetDiagnostics_sync", "segments": [ { "end": 52, @@ -22777,35 +22805,35 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_licenses_delete_sync.py" + "title": "compute_v1_generated_interconnects_get_diagnostics_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.LicensesClient", - "shortName": "LicensesClient" + "fullName": "google.cloud.compute_v1.InterconnectsClient", + "shortName": "InterconnectsClient" }, - "fullName": "google.cloud.compute_v1.LicensesClient.get_iam_policy", + "fullName": "google.cloud.compute_v1.InterconnectsClient.get_macsec_config", "method": { - "fullName": "google.cloud.compute.v1.Licenses.GetIamPolicy", + "fullName": "google.cloud.compute.v1.Interconnects.GetMacsecConfig", "service": { - "fullName": "google.cloud.compute.v1.Licenses", - "shortName": "Licenses" + "fullName": "google.cloud.compute.v1.Interconnects", + "shortName": "Interconnects" }, - "shortName": "GetIamPolicy" + "shortName": "GetMacsecConfig" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetIamPolicyLicenseRequest" + "type": "google.cloud.compute_v1.types.GetMacsecConfigInterconnectRequest" }, { "name": "project", "type": "str" }, { - "name": "resource", + "name": "interconnect", "type": "str" }, { @@ -22821,14 +22849,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "get_iam_policy" + "resultType": "google.cloud.compute_v1.types.InterconnectsGetMacsecConfigResponse", + "shortName": "get_macsec_config" }, - "description": "Sample for GetIamPolicy", - "file": "compute_v1_generated_licenses_get_iam_policy_sync.py", + "description": "Sample for GetMacsecConfig", + "file": "compute_v1_generated_interconnects_get_macsec_config_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Licenses_GetIamPolicy_sync", + "regionTag": "compute_v1_generated_Interconnects_GetMacsecConfig_sync", "segments": [ { "end": 52, @@ -22861,35 +22889,35 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_licenses_get_iam_policy_sync.py" + "title": "compute_v1_generated_interconnects_get_macsec_config_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.LicensesClient", - "shortName": "LicensesClient" + "fullName": "google.cloud.compute_v1.InterconnectsClient", + "shortName": "InterconnectsClient" }, - "fullName": "google.cloud.compute_v1.LicensesClient.get", + "fullName": "google.cloud.compute_v1.InterconnectsClient.get", "method": { - "fullName": "google.cloud.compute.v1.Licenses.Get", + "fullName": "google.cloud.compute.v1.Interconnects.Get", "service": { - "fullName": "google.cloud.compute.v1.Licenses", - "shortName": "Licenses" + "fullName": "google.cloud.compute.v1.Interconnects", + "shortName": "Interconnects" }, "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetLicenseRequest" + "type": "google.cloud.compute_v1.types.GetInterconnectRequest" }, { "name": "project", "type": "str" }, { - "name": "license_", + "name": "interconnect", "type": "str" }, { @@ -22905,14 +22933,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.License", + "resultType": "google.cloud.compute_v1.types.Interconnect", "shortName": "get" }, "description": "Sample for Get", - "file": "compute_v1_generated_licenses_get_sync.py", + "file": "compute_v1_generated_interconnects_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Licenses_Get_sync", + "regionTag": "compute_v1_generated_Interconnects_Get_sync", "segments": [ { "end": 52, @@ -22945,36 +22973,36 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_licenses_get_sync.py" + "title": "compute_v1_generated_interconnects_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.LicensesClient", - "shortName": "LicensesClient" + "fullName": "google.cloud.compute_v1.InterconnectsClient", + "shortName": "InterconnectsClient" }, - "fullName": "google.cloud.compute_v1.LicensesClient.insert", + "fullName": "google.cloud.compute_v1.InterconnectsClient.insert", "method": { - "fullName": "google.cloud.compute.v1.Licenses.Insert", + "fullName": "google.cloud.compute.v1.Interconnects.Insert", "service": { - "fullName": "google.cloud.compute.v1.Licenses", - "shortName": "Licenses" + "fullName": "google.cloud.compute.v1.Interconnects", + "shortName": "Interconnects" }, "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertLicenseRequest" + "type": "google.cloud.compute_v1.types.InsertInterconnectRequest" }, { "name": "project", "type": "str" }, { - "name": "license_resource", - "type": "google.cloud.compute_v1.types.License" + "name": "interconnect_resource", + "type": "google.cloud.compute_v1.types.Interconnect" }, { "name": "retry", @@ -22993,10 +23021,10 @@ "shortName": "insert" }, "description": "Sample for Insert", - "file": "compute_v1_generated_licenses_insert_sync.py", + "file": "compute_v1_generated_interconnects_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Licenses_Insert_sync", + "regionTag": "compute_v1_generated_Interconnects_Insert_sync", "segments": [ { "end": 51, @@ -23029,28 +23057,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_licenses_insert_sync.py" + "title": "compute_v1_generated_interconnects_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.LicensesClient", - "shortName": "LicensesClient" + "fullName": "google.cloud.compute_v1.InterconnectsClient", + "shortName": "InterconnectsClient" }, - "fullName": "google.cloud.compute_v1.LicensesClient.list", + "fullName": "google.cloud.compute_v1.InterconnectsClient.list", "method": { - "fullName": "google.cloud.compute.v1.Licenses.List", + "fullName": "google.cloud.compute.v1.Interconnects.List", "service": { - "fullName": "google.cloud.compute.v1.Licenses", - "shortName": "Licenses" + "fullName": "google.cloud.compute.v1.Interconnects", + "shortName": "Interconnects" }, "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListLicensesRequest" + "type": "google.cloud.compute_v1.types.ListInterconnectsRequest" }, { "name": "project", @@ -23069,14 +23097,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.licenses.pagers.ListPager", + "resultType": "google.cloud.compute_v1.services.interconnects.pagers.ListPager", "shortName": "list" }, "description": "Sample for List", - "file": "compute_v1_generated_licenses_list_sync.py", + "file": "compute_v1_generated_interconnects_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Licenses_List_sync", + "regionTag": "compute_v1_generated_Interconnects_List_sync", "segments": [ { "end": 52, @@ -23109,40 +23137,40 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_licenses_list_sync.py" + "title": "compute_v1_generated_interconnects_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.LicensesClient", - "shortName": "LicensesClient" + "fullName": "google.cloud.compute_v1.InterconnectsClient", + "shortName": "InterconnectsClient" }, - "fullName": "google.cloud.compute_v1.LicensesClient.set_iam_policy", + "fullName": "google.cloud.compute_v1.InterconnectsClient.patch", "method": { - "fullName": "google.cloud.compute.v1.Licenses.SetIamPolicy", + "fullName": "google.cloud.compute.v1.Interconnects.Patch", "service": { - "fullName": "google.cloud.compute.v1.Licenses", - "shortName": "Licenses" + "fullName": "google.cloud.compute.v1.Interconnects", + "shortName": "Interconnects" }, - "shortName": "SetIamPolicy" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetIamPolicyLicenseRequest" + "type": "google.cloud.compute_v1.types.PatchInterconnectRequest" }, { "name": "project", "type": "str" }, { - "name": "resource", + "name": "interconnect", "type": "str" }, { - "name": "global_set_policy_request_resource", - "type": "google.cloud.compute_v1.types.GlobalSetPolicyRequest" + "name": "interconnect_resource", + "type": "google.cloud.compute_v1.types.Interconnect" }, { "name": "retry", @@ -23157,14 +23185,778 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "set_iam_policy" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "patch" }, - "description": "Sample for SetIamPolicy", - "file": "compute_v1_generated_licenses_set_iam_policy_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_interconnects_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Licenses_SetIamPolicy_sync", + "regionTag": "compute_v1_generated_Interconnects_Patch_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_interconnects_patch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.InterconnectsClient", + "shortName": "InterconnectsClient" + }, + "fullName": "google.cloud.compute_v1.InterconnectsClient.set_labels", + "method": { + "fullName": "google.cloud.compute.v1.Interconnects.SetLabels", + "service": { + "fullName": "google.cloud.compute.v1.Interconnects", + "shortName": "Interconnects" + }, + "shortName": "SetLabels" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.SetLabelsInterconnectRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "global_set_labels_request_resource", + "type": "google.cloud.compute_v1.types.GlobalSetLabelsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "set_labels" + }, + "description": "Sample for SetLabels", + "file": "compute_v1_generated_interconnects_set_labels_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Interconnects_SetLabels_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_interconnects_set_labels_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.LicenseCodesClient", + "shortName": "LicenseCodesClient" + }, + "fullName": "google.cloud.compute_v1.LicenseCodesClient.get", + "method": { + "fullName": "google.cloud.compute.v1.LicenseCodes.Get", + "service": { + "fullName": "google.cloud.compute.v1.LicenseCodes", + "shortName": "LicenseCodes" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.GetLicenseCodeRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "license_code", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.compute_v1.types.LicenseCode", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1_generated_license_codes_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_LicenseCodes_Get_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_license_codes_get_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.LicenseCodesClient", + "shortName": "LicenseCodesClient" + }, + "fullName": "google.cloud.compute_v1.LicenseCodesClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.compute.v1.LicenseCodes.TestIamPermissions", + "service": { + "fullName": "google.cloud.compute.v1.LicenseCodes", + "shortName": "LicenseCodes" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.TestIamPermissionsLicenseCodeRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "compute_v1_generated_license_codes_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_LicenseCodes_TestIamPermissions_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_license_codes_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.LicensesClient", + "shortName": "LicensesClient" + }, + "fullName": "google.cloud.compute_v1.LicensesClient.delete", + "method": { + "fullName": "google.cloud.compute.v1.Licenses.Delete", + "service": { + "fullName": "google.cloud.compute.v1.Licenses", + "shortName": "Licenses" + }, + "shortName": "Delete" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.DeleteLicenseRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "license_", + "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.extended_operation.ExtendedOperation", + "shortName": "delete" + }, + "description": "Sample for Delete", + "file": "compute_v1_generated_licenses_delete_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Licenses_Delete_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_licenses_delete_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.LicensesClient", + "shortName": "LicensesClient" + }, + "fullName": "google.cloud.compute_v1.LicensesClient.get_iam_policy", + "method": { + "fullName": "google.cloud.compute.v1.Licenses.GetIamPolicy", + "service": { + "fullName": "google.cloud.compute.v1.Licenses", + "shortName": "Licenses" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.GetIamPolicyLicenseRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "compute_v1_generated_licenses_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Licenses_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_licenses_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.LicensesClient", + "shortName": "LicensesClient" + }, + "fullName": "google.cloud.compute_v1.LicensesClient.get", + "method": { + "fullName": "google.cloud.compute.v1.Licenses.Get", + "service": { + "fullName": "google.cloud.compute.v1.Licenses", + "shortName": "Licenses" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.GetLicenseRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "license_", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.compute_v1.types.License", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1_generated_licenses_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Licenses_Get_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_licenses_get_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.LicensesClient", + "shortName": "LicensesClient" + }, + "fullName": "google.cloud.compute_v1.LicensesClient.insert", + "method": { + "fullName": "google.cloud.compute.v1.Licenses.Insert", + "service": { + "fullName": "google.cloud.compute.v1.Licenses", + "shortName": "Licenses" + }, + "shortName": "Insert" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.InsertLicenseRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "license_resource", + "type": "google.cloud.compute_v1.types.License" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" + }, + "description": "Sample for Insert", + "file": "compute_v1_generated_licenses_insert_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Licenses_Insert_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_licenses_insert_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.LicensesClient", + "shortName": "LicensesClient" + }, + "fullName": "google.cloud.compute_v1.LicensesClient.list", + "method": { + "fullName": "google.cloud.compute.v1.Licenses.List", + "service": { + "fullName": "google.cloud.compute.v1.Licenses", + "shortName": "Licenses" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ListLicensesRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.compute_v1.services.licenses.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1_generated_licenses_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Licenses_List_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_licenses_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.LicensesClient", + "shortName": "LicensesClient" + }, + "fullName": "google.cloud.compute_v1.LicensesClient.set_iam_policy", + "method": { + "fullName": "google.cloud.compute.v1.Licenses.SetIamPolicy", + "service": { + "fullName": "google.cloud.compute.v1.Licenses", + "shortName": "Licenses" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.SetIamPolicyLicenseRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "global_set_policy_request_resource", + "type": "google.cloud.compute_v1.types.GlobalSetPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "compute_v1_generated_licenses_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Licenses_SetIamPolicy_sync", "segments": [ { "end": 52, @@ -23369,7 +24161,427 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_machine_images_delete_sync.py" + "title": "compute_v1_generated_machine_images_delete_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.MachineImagesClient", + "shortName": "MachineImagesClient" + }, + "fullName": "google.cloud.compute_v1.MachineImagesClient.get_iam_policy", + "method": { + "fullName": "google.cloud.compute.v1.MachineImages.GetIamPolicy", + "service": { + "fullName": "google.cloud.compute.v1.MachineImages", + "shortName": "MachineImages" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.GetIamPolicyMachineImageRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "compute_v1_generated_machine_images_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_MachineImages_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_machine_images_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.MachineImagesClient", + "shortName": "MachineImagesClient" + }, + "fullName": "google.cloud.compute_v1.MachineImagesClient.get", + "method": { + "fullName": "google.cloud.compute.v1.MachineImages.Get", + "service": { + "fullName": "google.cloud.compute.v1.MachineImages", + "shortName": "MachineImages" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.GetMachineImageRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "machine_image", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.compute_v1.types.MachineImage", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1_generated_machine_images_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_MachineImages_Get_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_machine_images_get_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.MachineImagesClient", + "shortName": "MachineImagesClient" + }, + "fullName": "google.cloud.compute_v1.MachineImagesClient.insert", + "method": { + "fullName": "google.cloud.compute.v1.MachineImages.Insert", + "service": { + "fullName": "google.cloud.compute.v1.MachineImages", + "shortName": "MachineImages" + }, + "shortName": "Insert" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.InsertMachineImageRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "machine_image_resource", + "type": "google.cloud.compute_v1.types.MachineImage" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" + }, + "description": "Sample for Insert", + "file": "compute_v1_generated_machine_images_insert_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_MachineImages_Insert_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_machine_images_insert_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.MachineImagesClient", + "shortName": "MachineImagesClient" + }, + "fullName": "google.cloud.compute_v1.MachineImagesClient.list", + "method": { + "fullName": "google.cloud.compute.v1.MachineImages.List", + "service": { + "fullName": "google.cloud.compute.v1.MachineImages", + "shortName": "MachineImages" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ListMachineImagesRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.compute_v1.services.machine_images.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1_generated_machine_images_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_MachineImages_List_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_machine_images_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.MachineImagesClient", + "shortName": "MachineImagesClient" + }, + "fullName": "google.cloud.compute_v1.MachineImagesClient.set_iam_policy", + "method": { + "fullName": "google.cloud.compute.v1.MachineImages.SetIamPolicy", + "service": { + "fullName": "google.cloud.compute.v1.MachineImages", + "shortName": "MachineImages" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.SetIamPolicyMachineImageRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "global_set_policy_request_resource", + "type": "google.cloud.compute_v1.types.GlobalSetPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "compute_v1_generated_machine_images_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_MachineImages_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_machine_images_set_iam_policy_sync.py" }, { "canonical": true, @@ -23378,19 +24590,19 @@ "fullName": "google.cloud.compute_v1.MachineImagesClient", "shortName": "MachineImagesClient" }, - "fullName": "google.cloud.compute_v1.MachineImagesClient.get_iam_policy", + "fullName": "google.cloud.compute_v1.MachineImagesClient.test_iam_permissions", "method": { - "fullName": "google.cloud.compute.v1.MachineImages.GetIamPolicy", + "fullName": "google.cloud.compute.v1.MachineImages.TestIamPermissions", "service": { "fullName": "google.cloud.compute.v1.MachineImages", "shortName": "MachineImages" }, - "shortName": "GetIamPolicy" + "shortName": "TestIamPermissions" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetIamPolicyMachineImageRequest" + "type": "google.cloud.compute_v1.types.TestIamPermissionsMachineImageRequest" }, { "name": "project", @@ -23400,6 +24612,10 @@ "name": "resource", "type": "str" }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -23413,14 +24629,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "get_iam_policy" + "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" }, - "description": "Sample for GetIamPolicy", - "file": "compute_v1_generated_machine_images_get_iam_policy_sync.py", + "description": "Sample for TestIamPermissions", + "file": "compute_v1_generated_machine_images_test_iam_permissions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_MachineImages_GetIamPolicy_sync", + "regionTag": "compute_v1_generated_MachineImages_TestIamPermissions_sync", "segments": [ { "end": 52, @@ -23453,37 +24669,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_machine_images_get_iam_policy_sync.py" + "title": "compute_v1_generated_machine_images_test_iam_permissions_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.MachineImagesClient", - "shortName": "MachineImagesClient" + "fullName": "google.cloud.compute_v1.MachineTypesClient", + "shortName": "MachineTypesClient" }, - "fullName": "google.cloud.compute_v1.MachineImagesClient.get", + "fullName": "google.cloud.compute_v1.MachineTypesClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1.MachineImages.Get", + "fullName": "google.cloud.compute.v1.MachineTypes.AggregatedList", "service": { - "fullName": "google.cloud.compute.v1.MachineImages", - "shortName": "MachineImages" + "fullName": "google.cloud.compute.v1.MachineTypes", + "shortName": "MachineTypes" }, - "shortName": "Get" + "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetMachineImageRequest" + "type": "google.cloud.compute_v1.types.AggregatedListMachineTypesRequest" }, { "name": "project", "type": "str" }, - { - "name": "machine_image", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -23497,14 +24709,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.MachineImage", - "shortName": "get" + "resultType": "google.cloud.compute_v1.services.machine_types.pagers.AggregatedListPager", + "shortName": "aggregated_list" }, - "description": "Sample for Get", - "file": "compute_v1_generated_machine_images_get_sync.py", + "description": "Sample for AggregatedList", + "file": "compute_v1_generated_machine_types_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_MachineImages_Get_sync", + "regionTag": "compute_v1_generated_MachineTypes_AggregatedList_sync", "segments": [ { "end": 52, @@ -23522,51 +24734,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_machine_images_get_sync.py" + "title": "compute_v1_generated_machine_types_aggregated_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.MachineImagesClient", - "shortName": "MachineImagesClient" + "fullName": "google.cloud.compute_v1.MachineTypesClient", + "shortName": "MachineTypesClient" }, - "fullName": "google.cloud.compute_v1.MachineImagesClient.insert", + "fullName": "google.cloud.compute_v1.MachineTypesClient.get", "method": { - "fullName": "google.cloud.compute.v1.MachineImages.Insert", + "fullName": "google.cloud.compute.v1.MachineTypes.Get", "service": { - "fullName": "google.cloud.compute.v1.MachineImages", - "shortName": "MachineImages" + "fullName": "google.cloud.compute.v1.MachineTypes", + "shortName": "MachineTypes" }, - "shortName": "Insert" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertMachineImageRequest" + "type": "google.cloud.compute_v1.types.GetMachineTypeRequest" }, { "name": "project", "type": "str" }, { - "name": "machine_image_resource", - "type": "google.cloud.compute_v1.types.MachineImage" + "name": "zone", + "type": "str" + }, + { + "name": "machine_type", + "type": "str" }, { "name": "retry", @@ -23581,22 +24797,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "resultType": "google.cloud.compute_v1.types.MachineType", + "shortName": "get" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_machine_images_insert_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_machine_types_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_MachineImages_Insert_sync", + "regionTag": "compute_v1_generated_MachineTypes_Get_sync", "segments": [ { - "end": 51, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 53, "start": 27, "type": "SHORT" }, @@ -23606,48 +24822,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_machine_images_insert_sync.py" + "title": "compute_v1_generated_machine_types_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.MachineImagesClient", - "shortName": "MachineImagesClient" + "fullName": "google.cloud.compute_v1.MachineTypesClient", + "shortName": "MachineTypesClient" }, - "fullName": "google.cloud.compute_v1.MachineImagesClient.list", + "fullName": "google.cloud.compute_v1.MachineTypesClient.list", "method": { - "fullName": "google.cloud.compute.v1.MachineImages.List", + "fullName": "google.cloud.compute.v1.MachineTypes.List", "service": { - "fullName": "google.cloud.compute.v1.MachineImages", - "shortName": "MachineImages" + "fullName": "google.cloud.compute.v1.MachineTypes", + "shortName": "MachineTypes" }, "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListMachineImagesRequest" + "type": "google.cloud.compute_v1.types.ListMachineTypesRequest" }, { "name": "project", "type": "str" }, + { + "name": "zone", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -23661,22 +24881,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.machine_images.pagers.ListPager", + "resultType": "google.cloud.compute_v1.services.machine_types.pagers.ListPager", "shortName": "list" }, "description": "Sample for List", - "file": "compute_v1_generated_machine_images_list_sync.py", + "file": "compute_v1_generated_machine_types_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_MachineImages_List_sync", + "regionTag": "compute_v1_generated_MachineTypes_List_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -23686,56 +24906,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 54, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_machine_images_list_sync.py" + "title": "compute_v1_generated_machine_types_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.MachineImagesClient", - "shortName": "MachineImagesClient" + "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient", + "shortName": "NetworkAttachmentsClient" }, - "fullName": "google.cloud.compute_v1.MachineImagesClient.set_iam_policy", + "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1.MachineImages.SetIamPolicy", + "fullName": "google.cloud.compute.v1.NetworkAttachments.AggregatedList", "service": { - "fullName": "google.cloud.compute.v1.MachineImages", - "shortName": "MachineImages" + "fullName": "google.cloud.compute.v1.NetworkAttachments", + "shortName": "NetworkAttachments" }, - "shortName": "SetIamPolicy" + "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetIamPolicyMachineImageRequest" + "type": "google.cloud.compute_v1.types.AggregatedListNetworkAttachmentsRequest" }, { "name": "project", "type": "str" }, - { - "name": "resource", - "type": "str" - }, - { - "name": "global_set_policy_request_resource", - "type": "google.cloud.compute_v1.types.GlobalSetPolicyRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -23749,14 +24961,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "set_iam_policy" + "resultType": "google.cloud.compute_v1.services.network_attachments.pagers.AggregatedListPager", + "shortName": "aggregated_list" }, - "description": "Sample for SetIamPolicy", - "file": "compute_v1_generated_machine_images_set_iam_policy_sync.py", + "description": "Sample for AggregatedList", + "file": "compute_v1_generated_network_attachments_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_MachineImages_SetIamPolicy_sync", + "regionTag": "compute_v1_generated_NetworkAttachments_AggregatedList_sync", "segments": [ { "end": 52, @@ -23774,55 +24986,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_machine_images_set_iam_policy_sync.py" + "title": "compute_v1_generated_network_attachments_aggregated_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.MachineImagesClient", - "shortName": "MachineImagesClient" + "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient", + "shortName": "NetworkAttachmentsClient" }, - "fullName": "google.cloud.compute_v1.MachineImagesClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.delete", "method": { - "fullName": "google.cloud.compute.v1.MachineImages.TestIamPermissions", + "fullName": "google.cloud.compute.v1.NetworkAttachments.Delete", "service": { - "fullName": "google.cloud.compute.v1.MachineImages", - "shortName": "MachineImages" + "fullName": "google.cloud.compute.v1.NetworkAttachments", + "shortName": "NetworkAttachments" }, - "shortName": "TestIamPermissions" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.TestIamPermissionsMachineImageRequest" + "type": "google.cloud.compute_v1.types.DeleteNetworkAttachmentRequest" }, { "name": "project", "type": "str" }, { - "name": "resource", + "name": "region", "type": "str" }, { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + "name": "network_attachment", + "type": "str" }, { "name": "retry", @@ -23837,22 +25049,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1_generated_machine_images_test_iam_permissions_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_network_attachments_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_MachineImages_TestIamPermissions_sync", + "regionTag": "compute_v1_generated_NetworkAttachments_Delete_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -23862,48 +25074,56 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_machine_images_test_iam_permissions_sync.py" + "title": "compute_v1_generated_network_attachments_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.MachineTypesClient", - "shortName": "MachineTypesClient" + "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient", + "shortName": "NetworkAttachmentsClient" }, - "fullName": "google.cloud.compute_v1.MachineTypesClient.aggregated_list", + "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.get_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.MachineTypes.AggregatedList", + "fullName": "google.cloud.compute.v1.NetworkAttachments.GetIamPolicy", "service": { - "fullName": "google.cloud.compute.v1.MachineTypes", - "shortName": "MachineTypes" + "fullName": "google.cloud.compute.v1.NetworkAttachments", + "shortName": "NetworkAttachments" }, - "shortName": "AggregatedList" + "shortName": "GetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AggregatedListMachineTypesRequest" + "type": "google.cloud.compute_v1.types.GetIamPolicyNetworkAttachmentRequest" }, { "name": "project", "type": "str" }, + { + "name": "region", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -23917,22 +25137,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.machine_types.pagers.AggregatedListPager", - "shortName": "aggregated_list" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "get_iam_policy" }, - "description": "Sample for AggregatedList", - "file": "compute_v1_generated_machine_types_aggregated_list_sync.py", + "description": "Sample for GetIamPolicy", + "file": "compute_v1_generated_network_attachments_get_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_MachineTypes_AggregatedList_sync", + "regionTag": "compute_v1_generated_NetworkAttachments_GetIamPolicy_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -23942,54 +25162,54 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_machine_types_aggregated_list_sync.py" + "title": "compute_v1_generated_network_attachments_get_iam_policy_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.MachineTypesClient", - "shortName": "MachineTypesClient" + "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient", + "shortName": "NetworkAttachmentsClient" }, - "fullName": "google.cloud.compute_v1.MachineTypesClient.get", + "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.get", "method": { - "fullName": "google.cloud.compute.v1.MachineTypes.Get", + "fullName": "google.cloud.compute.v1.NetworkAttachments.Get", "service": { - "fullName": "google.cloud.compute.v1.MachineTypes", - "shortName": "MachineTypes" + "fullName": "google.cloud.compute.v1.NetworkAttachments", + "shortName": "NetworkAttachments" }, "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetMachineTypeRequest" + "type": "google.cloud.compute_v1.types.GetNetworkAttachmentRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", + "name": "region", "type": "str" }, { - "name": "machine_type", + "name": "network_attachment", "type": "str" }, { @@ -24005,14 +25225,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.MachineType", + "resultType": "google.cloud.compute_v1.types.NetworkAttachment", "shortName": "get" }, "description": "Sample for Get", - "file": "compute_v1_generated_machine_types_get_sync.py", + "file": "compute_v1_generated_network_attachments_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_MachineTypes_Get_sync", + "regionTag": "compute_v1_generated_NetworkAttachments_Get_sync", "segments": [ { "end": 53, @@ -24045,37 +25265,41 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_machine_types_get_sync.py" + "title": "compute_v1_generated_network_attachments_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.MachineTypesClient", - "shortName": "MachineTypesClient" + "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient", + "shortName": "NetworkAttachmentsClient" }, - "fullName": "google.cloud.compute_v1.MachineTypesClient.list", + "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.insert", "method": { - "fullName": "google.cloud.compute.v1.MachineTypes.List", + "fullName": "google.cloud.compute.v1.NetworkAttachments.Insert", "service": { - "fullName": "google.cloud.compute.v1.MachineTypes", - "shortName": "MachineTypes" + "fullName": "google.cloud.compute.v1.NetworkAttachments", + "shortName": "NetworkAttachments" }, - "shortName": "List" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListMachineTypesRequest" + "type": "google.cloud.compute_v1.types.InsertNetworkAttachmentRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", + "name": "region", "type": "str" }, + { + "name": "network_attachment_resource", + "type": "google.cloud.compute_v1.types.NetworkAttachment" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -24089,22 +25313,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.machine_types.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" }, - "description": "Sample for List", - "file": "compute_v1_generated_machine_types_list_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_network_attachments_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_MachineTypes_List_sync", + "regionTag": "compute_v1_generated_NetworkAttachments_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -24124,12 +25348,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 54, + "end": 53, "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_machine_types_list_sync.py" + "title": "compute_v1_generated_network_attachments_insert_sync.py" }, { "canonical": true, @@ -24138,24 +25362,28 @@ "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient", "shortName": "NetworkAttachmentsClient" }, - "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.aggregated_list", + "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.list", "method": { - "fullName": "google.cloud.compute.v1.NetworkAttachments.AggregatedList", + "fullName": "google.cloud.compute.v1.NetworkAttachments.List", "service": { "fullName": "google.cloud.compute.v1.NetworkAttachments", "shortName": "NetworkAttachments" }, - "shortName": "AggregatedList" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AggregatedListNetworkAttachmentsRequest" + "type": "google.cloud.compute_v1.types.ListNetworkAttachmentsRequest" }, { "name": "project", "type": "str" }, + { + "name": "region", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -24169,22 +25397,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.network_attachments.pagers.AggregatedListPager", - "shortName": "aggregated_list" + "resultType": "google.cloud.compute_v1.services.network_attachments.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for AggregatedList", - "file": "compute_v1_generated_network_attachments_aggregated_list_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_network_attachments_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkAttachments_AggregatedList_sync", + "regionTag": "compute_v1_generated_NetworkAttachments_List_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -24194,22 +25422,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 54, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_attachments_aggregated_list_sync.py" + "title": "compute_v1_generated_network_attachments_list_sync.py" }, { "canonical": true, @@ -24218,19 +25446,19 @@ "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient", "shortName": "NetworkAttachmentsClient" }, - "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.delete", + "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.patch", "method": { - "fullName": "google.cloud.compute.v1.NetworkAttachments.Delete", + "fullName": "google.cloud.compute.v1.NetworkAttachments.Patch", "service": { "fullName": "google.cloud.compute.v1.NetworkAttachments", "shortName": "NetworkAttachments" }, - "shortName": "Delete" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteNetworkAttachmentRequest" + "type": "google.cloud.compute_v1.types.PatchNetworkAttachmentRequest" }, { "name": "project", @@ -24244,6 +25472,10 @@ "name": "network_attachment", "type": "str" }, + { + "name": "network_attachment_resource", + "type": "google.cloud.compute_v1.types.NetworkAttachment" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -24258,13 +25490,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "shortName": "patch" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_network_attachments_delete_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_network_attachments_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkAttachments_Delete_sync", + "regionTag": "compute_v1_generated_NetworkAttachments_Patch_sync", "segments": [ { "end": 53, @@ -24297,7 +25529,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_attachments_delete_sync.py" + "title": "compute_v1_generated_network_attachments_patch_sync.py" }, { "canonical": true, @@ -24306,19 +25538,19 @@ "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient", "shortName": "NetworkAttachmentsClient" }, - "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.get_iam_policy", + "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.set_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.NetworkAttachments.GetIamPolicy", + "fullName": "google.cloud.compute.v1.NetworkAttachments.SetIamPolicy", "service": { "fullName": "google.cloud.compute.v1.NetworkAttachments", "shortName": "NetworkAttachments" }, - "shortName": "GetIamPolicy" + "shortName": "SetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetIamPolicyNetworkAttachmentRequest" + "type": "google.cloud.compute_v1.types.SetIamPolicyNetworkAttachmentRequest" }, { "name": "project", @@ -24332,6 +25564,10 @@ "name": "resource", "type": "str" }, + { + "name": "region_set_policy_request_resource", + "type": "google.cloud.compute_v1.types.RegionSetPolicyRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -24346,13 +25582,13 @@ } ], "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "get_iam_policy" + "shortName": "set_iam_policy" }, - "description": "Sample for GetIamPolicy", - "file": "compute_v1_generated_network_attachments_get_iam_policy_sync.py", + "description": "Sample for SetIamPolicy", + "file": "compute_v1_generated_network_attachments_set_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkAttachments_GetIamPolicy_sync", + "regionTag": "compute_v1_generated_NetworkAttachments_SetIamPolicy_sync", "segments": [ { "end": 53, @@ -24385,7 +25621,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_attachments_get_iam_policy_sync.py" + "title": "compute_v1_generated_network_attachments_set_iam_policy_sync.py" }, { "canonical": true, @@ -24394,19 +25630,19 @@ "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient", "shortName": "NetworkAttachmentsClient" }, - "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.get", + "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.test_iam_permissions", "method": { - "fullName": "google.cloud.compute.v1.NetworkAttachments.Get", + "fullName": "google.cloud.compute.v1.NetworkAttachments.TestIamPermissions", "service": { "fullName": "google.cloud.compute.v1.NetworkAttachments", "shortName": "NetworkAttachments" }, - "shortName": "Get" + "shortName": "TestIamPermissions" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetNetworkAttachmentRequest" + "type": "google.cloud.compute_v1.types.TestIamPermissionsNetworkAttachmentRequest" }, { "name": "project", @@ -24417,9 +25653,13 @@ "type": "str" }, { - "name": "network_attachment", + "name": "resource", "type": "str" }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -24433,14 +25673,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.NetworkAttachment", - "shortName": "get" + "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" }, - "description": "Sample for Get", - "file": "compute_v1_generated_network_attachments_get_sync.py", + "description": "Sample for TestIamPermissions", + "file": "compute_v1_generated_network_attachments_test_iam_permissions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkAttachments_Get_sync", + "regionTag": "compute_v1_generated_NetworkAttachments_TestIamPermissions_sync", "segments": [ { "end": 53, @@ -24473,41 +25713,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_attachments_get_sync.py" + "title": "compute_v1_generated_network_attachments_test_iam_permissions_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient", - "shortName": "NetworkAttachmentsClient" + "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient", + "shortName": "NetworkEdgeSecurityServicesClient" }, - "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.insert", + "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1.NetworkAttachments.Insert", + "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices.AggregatedList", "service": { - "fullName": "google.cloud.compute.v1.NetworkAttachments", - "shortName": "NetworkAttachments" + "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices", + "shortName": "NetworkEdgeSecurityServices" }, - "shortName": "Insert" + "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertNetworkAttachmentRequest" + "type": "google.cloud.compute_v1.types.AggregatedListNetworkEdgeSecurityServicesRequest" }, { "name": "project", "type": "str" }, - { - "name": "region", - "type": "str" - }, - { - "name": "network_attachment_resource", - "type": "google.cloud.compute_v1.types.NetworkAttachment" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -24521,14 +25753,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "resultType": "google.cloud.compute_v1.services.network_edge_security_services.pagers.AggregatedListPager", + "shortName": "aggregated_list" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_network_attachments_insert_sync.py", + "description": "Sample for AggregatedList", + "file": "compute_v1_generated_network_edge_security_services_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkAttachments_Insert_sync", + "regionTag": "compute_v1_generated_NetworkEdgeSecurityServices_AggregatedList_sync", "segments": [ { "end": 52, @@ -24546,43 +25778,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_attachments_insert_sync.py" + "title": "compute_v1_generated_network_edge_security_services_aggregated_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient", - "shortName": "NetworkAttachmentsClient" + "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient", + "shortName": "NetworkEdgeSecurityServicesClient" }, - "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.list", + "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient.delete", "method": { - "fullName": "google.cloud.compute.v1.NetworkAttachments.List", + "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices.Delete", "service": { - "fullName": "google.cloud.compute.v1.NetworkAttachments", - "shortName": "NetworkAttachments" + "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices", + "shortName": "NetworkEdgeSecurityServices" }, - "shortName": "List" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListNetworkAttachmentsRequest" + "type": "google.cloud.compute_v1.types.DeleteNetworkEdgeSecurityServiceRequest" }, { "name": "project", @@ -24592,6 +25824,10 @@ "name": "region", "type": "str" }, + { + "name": "network_edge_security_service", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -24605,14 +25841,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.network_attachments.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for List", - "file": "compute_v1_generated_network_attachments_list_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_network_edge_security_services_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkAttachments_List_sync", + "regionTag": "compute_v1_generated_NetworkEdgeSecurityServices_Delete_sync", "segments": [ { "end": 53, @@ -24630,43 +25866,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 50, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_attachments_list_sync.py" + "title": "compute_v1_generated_network_edge_security_services_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient", - "shortName": "NetworkAttachmentsClient" + "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient", + "shortName": "NetworkEdgeSecurityServicesClient" }, - "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.patch", + "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient.get", "method": { - "fullName": "google.cloud.compute.v1.NetworkAttachments.Patch", + "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices.Get", "service": { - "fullName": "google.cloud.compute.v1.NetworkAttachments", - "shortName": "NetworkAttachments" + "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices", + "shortName": "NetworkEdgeSecurityServices" }, - "shortName": "Patch" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchNetworkAttachmentRequest" + "type": "google.cloud.compute_v1.types.GetNetworkEdgeSecurityServiceRequest" }, { "name": "project", @@ -24677,13 +25913,9 @@ "type": "str" }, { - "name": "network_attachment", + "name": "network_edge_security_service", "type": "str" }, - { - "name": "network_attachment_resource", - "type": "google.cloud.compute_v1.types.NetworkAttachment" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -24697,14 +25929,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "resultType": "google.cloud.compute_v1.types.NetworkEdgeSecurityService", + "shortName": "get" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_network_attachments_patch_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_network_edge_security_services_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkAttachments_Patch_sync", + "regionTag": "compute_v1_generated_NetworkEdgeSecurityServices_Get_sync", "segments": [ { "end": 53, @@ -24737,28 +25969,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_attachments_patch_sync.py" + "title": "compute_v1_generated_network_edge_security_services_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient", - "shortName": "NetworkAttachmentsClient" + "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient", + "shortName": "NetworkEdgeSecurityServicesClient" }, - "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.set_iam_policy", + "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient.insert", "method": { - "fullName": "google.cloud.compute.v1.NetworkAttachments.SetIamPolicy", + "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices.Insert", "service": { - "fullName": "google.cloud.compute.v1.NetworkAttachments", - "shortName": "NetworkAttachments" + "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices", + "shortName": "NetworkEdgeSecurityServices" }, - "shortName": "SetIamPolicy" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetIamPolicyNetworkAttachmentRequest" + "type": "google.cloud.compute_v1.types.InsertNetworkEdgeSecurityServiceRequest" }, { "name": "project", @@ -24769,12 +26001,8 @@ "type": "str" }, { - "name": "resource", - "type": "str" - }, - { - "name": "region_set_policy_request_resource", - "type": "google.cloud.compute_v1.types.RegionSetPolicyRequest" + "name": "network_edge_security_service_resource", + "type": "google.cloud.compute_v1.types.NetworkEdgeSecurityService" }, { "name": "retry", @@ -24789,22 +26017,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "set_iam_policy" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" }, - "description": "Sample for SetIamPolicy", - "file": "compute_v1_generated_network_attachments_set_iam_policy_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_network_edge_security_services_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkAttachments_SetIamPolicy_sync", + "regionTag": "compute_v1_generated_NetworkEdgeSecurityServices_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -24814,43 +26042,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_attachments_set_iam_policy_sync.py" + "title": "compute_v1_generated_network_edge_security_services_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient", - "shortName": "NetworkAttachmentsClient" + "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient", + "shortName": "NetworkEdgeSecurityServicesClient" }, - "fullName": "google.cloud.compute_v1.NetworkAttachmentsClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient.patch", "method": { - "fullName": "google.cloud.compute.v1.NetworkAttachments.TestIamPermissions", + "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices.Patch", "service": { - "fullName": "google.cloud.compute.v1.NetworkAttachments", - "shortName": "NetworkAttachments" + "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices", + "shortName": "NetworkEdgeSecurityServices" }, - "shortName": "TestIamPermissions" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.TestIamPermissionsNetworkAttachmentRequest" + "type": "google.cloud.compute_v1.types.PatchNetworkEdgeSecurityServiceRequest" }, { "name": "project", @@ -24861,12 +26089,12 @@ "type": "str" }, { - "name": "resource", + "name": "network_edge_security_service", "type": "str" }, { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + "name": "network_edge_security_service_resource", + "type": "google.cloud.compute_v1.types.NetworkEdgeSecurityService" }, { "name": "retry", @@ -24881,14 +26109,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "patch" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1_generated_network_attachments_test_iam_permissions_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_network_edge_security_services_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkAttachments_TestIamPermissions_sync", + "regionTag": "compute_v1_generated_NetworkEdgeSecurityServices_Patch_sync", "segments": [ { "end": 53, @@ -24921,28 +26149,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_attachments_test_iam_permissions_sync.py" + "title": "compute_v1_generated_network_edge_security_services_patch_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient", - "shortName": "NetworkEdgeSecurityServicesClient" + "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient", + "shortName": "NetworkEndpointGroupsClient" }, - "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient.aggregated_list", + "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices.AggregatedList", + "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.AggregatedList", "service": { - "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices", - "shortName": "NetworkEdgeSecurityServices" + "fullName": "google.cloud.compute.v1.NetworkEndpointGroups", + "shortName": "NetworkEndpointGroups" }, "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AggregatedListNetworkEdgeSecurityServicesRequest" + "type": "google.cloud.compute_v1.types.AggregatedListNetworkEndpointGroupsRequest" }, { "name": "project", @@ -24961,14 +26189,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.network_edge_security_services.pagers.AggregatedListPager", + "resultType": "google.cloud.compute_v1.services.network_endpoint_groups.pagers.AggregatedListPager", "shortName": "aggregated_list" }, "description": "Sample for AggregatedList", - "file": "compute_v1_generated_network_edge_security_services_aggregated_list_sync.py", + "file": "compute_v1_generated_network_endpoint_groups_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkEdgeSecurityServices_AggregatedList_sync", + "regionTag": "compute_v1_generated_NetworkEndpointGroups_AggregatedList_sync", "segments": [ { "end": 52, @@ -25001,41 +26229,45 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_edge_security_services_aggregated_list_sync.py" + "title": "compute_v1_generated_network_endpoint_groups_aggregated_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient", - "shortName": "NetworkEdgeSecurityServicesClient" + "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient", + "shortName": "NetworkEndpointGroupsClient" }, - "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient.delete", + "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.attach_network_endpoints", "method": { - "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices.Delete", + "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.AttachNetworkEndpoints", "service": { - "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices", - "shortName": "NetworkEdgeSecurityServices" + "fullName": "google.cloud.compute.v1.NetworkEndpointGroups", + "shortName": "NetworkEndpointGroups" }, - "shortName": "Delete" + "shortName": "AttachNetworkEndpoints" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteNetworkEdgeSecurityServiceRequest" + "type": "google.cloud.compute_v1.types.AttachNetworkEndpointsNetworkEndpointGroupRequest" }, { "name": "project", "type": "str" }, { - "name": "region", + "name": "zone", "type": "str" }, { - "name": "network_edge_security_service", + "name": "network_endpoint_group", "type": "str" }, + { + "name": "network_endpoint_groups_attach_endpoints_request_resource", + "type": "google.cloud.compute_v1.types.NetworkEndpointGroupsAttachEndpointsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -25050,13 +26282,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "shortName": "attach_network_endpoints" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_network_edge_security_services_delete_sync.py", + "description": "Sample for AttachNetworkEndpoints", + "file": "compute_v1_generated_network_endpoint_groups_attach_network_endpoints_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkEdgeSecurityServices_Delete_sync", + "regionTag": "compute_v1_generated_NetworkEndpointGroups_AttachNetworkEndpoints_sync", "segments": [ { "end": 53, @@ -25089,39 +26321,39 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_edge_security_services_delete_sync.py" + "title": "compute_v1_generated_network_endpoint_groups_attach_network_endpoints_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient", - "shortName": "NetworkEdgeSecurityServicesClient" + "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient", + "shortName": "NetworkEndpointGroupsClient" }, - "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient.get", + "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.delete", "method": { - "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices.Get", + "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.Delete", "service": { - "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices", - "shortName": "NetworkEdgeSecurityServices" + "fullName": "google.cloud.compute.v1.NetworkEndpointGroups", + "shortName": "NetworkEndpointGroups" }, - "shortName": "Get" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetNetworkEdgeSecurityServiceRequest" + "type": "google.cloud.compute_v1.types.DeleteNetworkEndpointGroupRequest" }, { "name": "project", "type": "str" }, { - "name": "region", + "name": "zone", "type": "str" }, { - "name": "network_edge_security_service", + "name": "network_endpoint_group", "type": "str" }, { @@ -25137,14 +26369,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.NetworkEdgeSecurityService", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for Get", - "file": "compute_v1_generated_network_edge_security_services_get_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_network_endpoint_groups_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkEdgeSecurityServices_Get_sync", + "regionTag": "compute_v1_generated_NetworkEndpointGroups_Delete_sync", "segments": [ { "end": 53, @@ -25177,132 +26409,44 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_edge_security_services_get_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient", - "shortName": "NetworkEdgeSecurityServicesClient" - }, - "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient.insert", - "method": { - "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices.Insert", - "service": { - "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices", - "shortName": "NetworkEdgeSecurityServices" - }, - "shortName": "Insert" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.compute_v1.types.InsertNetworkEdgeSecurityServiceRequest" - }, - { - "name": "project", - "type": "str" - }, - { - "name": "region", - "type": "str" - }, - { - "name": "network_edge_security_service_resource", - "type": "google.cloud.compute_v1.types.NetworkEdgeSecurityService" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" - }, - "description": "Sample for Insert", - "file": "compute_v1_generated_network_edge_security_services_insert_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkEdgeSecurityServices_Insert_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "compute_v1_generated_network_edge_security_services_insert_sync.py" + "title": "compute_v1_generated_network_endpoint_groups_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient", - "shortName": "NetworkEdgeSecurityServicesClient" + "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient", + "shortName": "NetworkEndpointGroupsClient" }, - "fullName": "google.cloud.compute_v1.NetworkEdgeSecurityServicesClient.patch", + "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.detach_network_endpoints", "method": { - "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices.Patch", + "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.DetachNetworkEndpoints", "service": { - "fullName": "google.cloud.compute.v1.NetworkEdgeSecurityServices", - "shortName": "NetworkEdgeSecurityServices" + "fullName": "google.cloud.compute.v1.NetworkEndpointGroups", + "shortName": "NetworkEndpointGroups" }, - "shortName": "Patch" + "shortName": "DetachNetworkEndpoints" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchNetworkEdgeSecurityServiceRequest" + "type": "google.cloud.compute_v1.types.DetachNetworkEndpointsNetworkEndpointGroupRequest" }, { "name": "project", "type": "str" }, { - "name": "region", + "name": "zone", "type": "str" }, { - "name": "network_edge_security_service", + "name": "network_endpoint_group", "type": "str" }, { - "name": "network_edge_security_service_resource", - "type": "google.cloud.compute_v1.types.NetworkEdgeSecurityService" + "name": "network_endpoint_groups_detach_endpoints_request_resource", + "type": "google.cloud.compute_v1.types.NetworkEndpointGroupsDetachEndpointsRequest" }, { "name": "retry", @@ -25318,13 +26462,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "shortName": "detach_network_endpoints" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_network_edge_security_services_patch_sync.py", + "description": "Sample for DetachNetworkEndpoints", + "file": "compute_v1_generated_network_endpoint_groups_detach_network_endpoints_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkEdgeSecurityServices_Patch_sync", + "regionTag": "compute_v1_generated_NetworkEndpointGroups_DetachNetworkEndpoints_sync", "segments": [ { "end": 53, @@ -25357,7 +26501,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_edge_security_services_patch_sync.py" + "title": "compute_v1_generated_network_endpoint_groups_detach_network_endpoints_sync.py" }, { "canonical": true, @@ -25366,24 +26510,32 @@ "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient", "shortName": "NetworkEndpointGroupsClient" }, - "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.aggregated_list", + "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.get", "method": { - "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.AggregatedList", + "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.Get", "service": { "fullName": "google.cloud.compute.v1.NetworkEndpointGroups", "shortName": "NetworkEndpointGroups" }, - "shortName": "AggregatedList" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AggregatedListNetworkEndpointGroupsRequest" + "type": "google.cloud.compute_v1.types.GetNetworkEndpointGroupRequest" }, { "name": "project", "type": "str" }, + { + "name": "zone", + "type": "str" + }, + { + "name": "network_endpoint_group", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -25397,22 +26549,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.network_endpoint_groups.pagers.AggregatedListPager", - "shortName": "aggregated_list" + "resultType": "google.cloud.compute_v1.types.NetworkEndpointGroup", + "shortName": "get" }, - "description": "Sample for AggregatedList", - "file": "compute_v1_generated_network_endpoint_groups_aggregated_list_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_network_endpoint_groups_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkEndpointGroups_AggregatedList_sync", + "regionTag": "compute_v1_generated_NetworkEndpointGroups_Get_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -25422,22 +26574,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_endpoint_groups_aggregated_list_sync.py" + "title": "compute_v1_generated_network_endpoint_groups_get_sync.py" }, { "canonical": true, @@ -25446,19 +26598,19 @@ "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient", "shortName": "NetworkEndpointGroupsClient" }, - "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.attach_network_endpoints", + "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.insert", "method": { - "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.AttachNetworkEndpoints", + "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.Insert", "service": { "fullName": "google.cloud.compute.v1.NetworkEndpointGroups", "shortName": "NetworkEndpointGroups" }, - "shortName": "AttachNetworkEndpoints" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AttachNetworkEndpointsNetworkEndpointGroupRequest" + "type": "google.cloud.compute_v1.types.InsertNetworkEndpointGroupRequest" }, { "name": "project", @@ -25469,12 +26621,8 @@ "type": "str" }, { - "name": "network_endpoint_group", - "type": "str" - }, - { - "name": "network_endpoint_groups_attach_endpoints_request_resource", - "type": "google.cloud.compute_v1.types.NetworkEndpointGroupsAttachEndpointsRequest" + "name": "network_endpoint_group_resource", + "type": "google.cloud.compute_v1.types.NetworkEndpointGroup" }, { "name": "retry", @@ -25490,21 +26638,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "attach_network_endpoints" + "shortName": "insert" }, - "description": "Sample for AttachNetworkEndpoints", - "file": "compute_v1_generated_network_endpoint_groups_attach_network_endpoints_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_network_endpoint_groups_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkEndpointGroups_AttachNetworkEndpoints_sync", + "regionTag": "compute_v1_generated_NetworkEndpointGroups_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -25514,22 +26662,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_endpoint_groups_attach_network_endpoints_sync.py" + "title": "compute_v1_generated_network_endpoint_groups_insert_sync.py" }, { "canonical": true, @@ -25538,19 +26686,19 @@ "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient", "shortName": "NetworkEndpointGroupsClient" }, - "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.delete", + "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.list_network_endpoints", "method": { - "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.Delete", + "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.ListNetworkEndpoints", "service": { "fullName": "google.cloud.compute.v1.NetworkEndpointGroups", "shortName": "NetworkEndpointGroups" }, - "shortName": "Delete" + "shortName": "ListNetworkEndpoints" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteNetworkEndpointGroupRequest" + "type": "google.cloud.compute_v1.types.ListNetworkEndpointsNetworkEndpointGroupsRequest" }, { "name": "project", @@ -25564,6 +26712,10 @@ "name": "network_endpoint_group", "type": "str" }, + { + "name": "network_endpoint_groups_list_endpoints_request_resource", + "type": "google.cloud.compute_v1.types.NetworkEndpointGroupsListEndpointsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -25577,22 +26729,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "resultType": "google.cloud.compute_v1.services.network_endpoint_groups.pagers.ListNetworkEndpointsPager", + "shortName": "list_network_endpoints" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_network_endpoint_groups_delete_sync.py", + "description": "Sample for ListNetworkEndpoints", + "file": "compute_v1_generated_network_endpoint_groups_list_network_endpoints_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkEndpointGroups_Delete_sync", + "regionTag": "compute_v1_generated_NetworkEndpointGroups_ListNetworkEndpoints_sync", "segments": [ { - "end": 53, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 54, "start": 27, "type": "SHORT" }, @@ -25612,12 +26764,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 54, + "end": 55, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_endpoint_groups_delete_sync.py" + "title": "compute_v1_generated_network_endpoint_groups_list_network_endpoints_sync.py" }, { "canonical": true, @@ -25626,19 +26778,19 @@ "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient", "shortName": "NetworkEndpointGroupsClient" }, - "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.detach_network_endpoints", + "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.list", "method": { - "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.DetachNetworkEndpoints", + "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.List", "service": { "fullName": "google.cloud.compute.v1.NetworkEndpointGroups", "shortName": "NetworkEndpointGroups" }, - "shortName": "DetachNetworkEndpoints" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DetachNetworkEndpointsNetworkEndpointGroupRequest" + "type": "google.cloud.compute_v1.types.ListNetworkEndpointGroupsRequest" }, { "name": "project", @@ -25648,14 +26800,6 @@ "name": "zone", "type": "str" }, - { - "name": "network_endpoint_group", - "type": "str" - }, - { - "name": "network_endpoint_groups_detach_endpoints_request_resource", - "type": "google.cloud.compute_v1.types.NetworkEndpointGroupsDetachEndpointsRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -25669,14 +26813,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "detach_network_endpoints" + "resultType": "google.cloud.compute_v1.services.network_endpoint_groups.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for DetachNetworkEndpoints", - "file": "compute_v1_generated_network_endpoint_groups_detach_network_endpoints_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_network_endpoint_groups_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkEndpointGroups_DetachNetworkEndpoints_sync", + "regionTag": "compute_v1_generated_NetworkEndpointGroups_List_sync", "segments": [ { "end": 53, @@ -25694,22 +26838,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 51, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_endpoint_groups_detach_network_endpoints_sync.py" + "title": "compute_v1_generated_network_endpoint_groups_list_sync.py" }, { "canonical": true, @@ -25718,19 +26862,19 @@ "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient", "shortName": "NetworkEndpointGroupsClient" }, - "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.get", + "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.test_iam_permissions", "method": { - "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.Get", + "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.TestIamPermissions", "service": { "fullName": "google.cloud.compute.v1.NetworkEndpointGroups", "shortName": "NetworkEndpointGroups" }, - "shortName": "Get" + "shortName": "TestIamPermissions" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetNetworkEndpointGroupRequest" + "type": "google.cloud.compute_v1.types.TestIamPermissionsNetworkEndpointGroupRequest" }, { "name": "project", @@ -25741,9 +26885,13 @@ "type": "str" }, { - "name": "network_endpoint_group", + "name": "resource", "type": "str" }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -25757,14 +26905,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.NetworkEndpointGroup", - "shortName": "get" + "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" }, - "description": "Sample for Get", - "file": "compute_v1_generated_network_endpoint_groups_get_sync.py", + "description": "Sample for TestIamPermissions", + "file": "compute_v1_generated_network_endpoint_groups_test_iam_permissions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkEndpointGroups_Get_sync", + "regionTag": "compute_v1_generated_NetworkEndpointGroups_TestIamPermissions_sync", "segments": [ { "end": 53, @@ -25797,40 +26945,40 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_endpoint_groups_get_sync.py" + "title": "compute_v1_generated_network_endpoint_groups_test_iam_permissions_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient", - "shortName": "NetworkEndpointGroupsClient" + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", + "shortName": "NetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.insert", + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.add_association", "method": { - "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.Insert", + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.AddAssociation", "service": { - "fullName": "google.cloud.compute.v1.NetworkEndpointGroups", - "shortName": "NetworkEndpointGroups" + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", + "shortName": "NetworkFirewallPolicies" }, - "shortName": "Insert" + "shortName": "AddAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertNetworkEndpointGroupRequest" + "type": "google.cloud.compute_v1.types.AddAssociationNetworkFirewallPolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", + "name": "firewall_policy", "type": "str" }, { - "name": "network_endpoint_group_resource", - "type": "google.cloud.compute_v1.types.NetworkEndpointGroup" + "name": "firewall_policy_association_resource", + "type": "google.cloud.compute_v1.types.FirewallPolicyAssociation" }, { "name": "retry", @@ -25846,13 +26994,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "shortName": "add_association" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_network_endpoint_groups_insert_sync.py", + "description": "Sample for AddAssociation", + "file": "compute_v1_generated_network_firewall_policies_add_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkEndpointGroups_Insert_sync", + "regionTag": "compute_v1_generated_NetworkFirewallPolicies_AddAssociation_sync", "segments": [ { "end": 52, @@ -25885,44 +27033,40 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_endpoint_groups_insert_sync.py" + "title": "compute_v1_generated_network_firewall_policies_add_association_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient", - "shortName": "NetworkEndpointGroupsClient" + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", + "shortName": "NetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.list_network_endpoints", + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.add_rule", "method": { - "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.ListNetworkEndpoints", + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.AddRule", "service": { - "fullName": "google.cloud.compute.v1.NetworkEndpointGroups", - "shortName": "NetworkEndpointGroups" + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", + "shortName": "NetworkFirewallPolicies" }, - "shortName": "ListNetworkEndpoints" + "shortName": "AddRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListNetworkEndpointsNetworkEndpointGroupsRequest" + "type": "google.cloud.compute_v1.types.AddRuleNetworkFirewallPolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", - "type": "str" - }, - { - "name": "network_endpoint_group", + "name": "firewall_policy", "type": "str" }, { - "name": "network_endpoint_groups_list_endpoints_request_resource", - "type": "google.cloud.compute_v1.types.NetworkEndpointGroupsListEndpointsRequest" + "name": "firewall_policy_rule_resource", + "type": "google.cloud.compute_v1.types.FirewallPolicyRule" }, { "name": "retry", @@ -25937,22 +27081,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.network_endpoint_groups.pagers.ListNetworkEndpointsPager", - "shortName": "list_network_endpoints" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "add_rule" }, - "description": "Sample for ListNetworkEndpoints", - "file": "compute_v1_generated_network_endpoint_groups_list_network_endpoints_sync.py", + "description": "Sample for AddRule", + "file": "compute_v1_generated_network_firewall_policies_add_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkEndpointGroups_ListNetworkEndpoints_sync", + "regionTag": "compute_v1_generated_NetworkFirewallPolicies_AddRule_sync", "segments": [ { - "end": 54, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 52, "start": 27, "type": "SHORT" }, @@ -25962,50 +27106,50 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_endpoint_groups_list_network_endpoints_sync.py" + "title": "compute_v1_generated_network_firewall_policies_add_rule_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient", - "shortName": "NetworkEndpointGroupsClient" + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", + "shortName": "NetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.list", + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.clone_rules", "method": { - "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.List", + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.CloneRules", "service": { - "fullName": "google.cloud.compute.v1.NetworkEndpointGroups", - "shortName": "NetworkEndpointGroups" + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", + "shortName": "NetworkFirewallPolicies" }, - "shortName": "List" + "shortName": "CloneRules" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListNetworkEndpointGroupsRequest" + "type": "google.cloud.compute_v1.types.CloneRulesNetworkFirewallPolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", + "name": "firewall_policy", "type": "str" }, { @@ -26021,22 +27165,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.network_endpoint_groups.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "clone_rules" }, - "description": "Sample for List", - "file": "compute_v1_generated_network_endpoint_groups_list_sync.py", + "description": "Sample for CloneRules", + "file": "compute_v1_generated_network_firewall_policies_clone_rules_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkEndpointGroups_List_sync", + "regionTag": "compute_v1_generated_NetworkFirewallPolicies_CloneRules_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -26056,50 +27200,42 @@ "type": "REQUEST_EXECUTION" }, { - "end": 54, + "end": 53, "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_endpoint_groups_list_sync.py" + "title": "compute_v1_generated_network_firewall_policies_clone_rules_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient", - "shortName": "NetworkEndpointGroupsClient" + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", + "shortName": "NetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1.NetworkEndpointGroupsClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.delete", "method": { - "fullName": "google.cloud.compute.v1.NetworkEndpointGroups.TestIamPermissions", + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.Delete", "service": { - "fullName": "google.cloud.compute.v1.NetworkEndpointGroups", - "shortName": "NetworkEndpointGroups" + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", + "shortName": "NetworkFirewallPolicies" }, - "shortName": "TestIamPermissions" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.TestIamPermissionsNetworkEndpointGroupRequest" + "type": "google.cloud.compute_v1.types.DeleteNetworkFirewallPolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", - "type": "str" - }, - { - "name": "resource", + "name": "firewall_policy", "type": "str" }, - { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1.types.TestPermissionsRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -26113,22 +27249,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1_generated_network_endpoint_groups_test_iam_permissions_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_network_firewall_policies_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkEndpointGroups_TestIamPermissions_sync", + "regionTag": "compute_v1_generated_NetworkFirewallPolicies_Delete_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -26138,22 +27274,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_endpoint_groups_test_iam_permissions_sync.py" + "title": "compute_v1_generated_network_firewall_policies_delete_sync.py" }, { "canonical": true, @@ -26162,19 +27298,19 @@ "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", "shortName": "NetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.add_association", + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.get_association", "method": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.AddAssociation", + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.GetAssociation", "service": { "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", "shortName": "NetworkFirewallPolicies" }, - "shortName": "AddAssociation" + "shortName": "GetAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AddAssociationNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1.types.GetAssociationNetworkFirewallPolicyRequest" }, { "name": "project", @@ -26184,10 +27320,6 @@ "name": "firewall_policy", "type": "str" }, - { - "name": "firewall_policy_association_resource", - "type": "google.cloud.compute_v1.types.FirewallPolicyAssociation" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -26201,14 +27333,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "add_association" + "resultType": "google.cloud.compute_v1.types.FirewallPolicyAssociation", + "shortName": "get_association" }, - "description": "Sample for AddAssociation", - "file": "compute_v1_generated_network_firewall_policies_add_association_sync.py", + "description": "Sample for GetAssociation", + "file": "compute_v1_generated_network_firewall_policies_get_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkFirewallPolicies_AddAssociation_sync", + "regionTag": "compute_v1_generated_NetworkFirewallPolicies_GetAssociation_sync", "segments": [ { "end": 52, @@ -26241,7 +27373,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_firewall_policies_add_association_sync.py" + "title": "compute_v1_generated_network_firewall_policies_get_association_sync.py" }, { "canonical": true, @@ -26250,32 +27382,28 @@ "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", "shortName": "NetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.add_rule", + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.get_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.AddRule", + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.GetIamPolicy", "service": { "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", "shortName": "NetworkFirewallPolicies" }, - "shortName": "AddRule" + "shortName": "GetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AddRuleNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1.types.GetIamPolicyNetworkFirewallPolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "firewall_policy", + "name": "resource", "type": "str" }, - { - "name": "firewall_policy_rule_resource", - "type": "google.cloud.compute_v1.types.FirewallPolicyRule" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -26289,14 +27417,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "add_rule" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "get_iam_policy" }, - "description": "Sample for AddRule", - "file": "compute_v1_generated_network_firewall_policies_add_rule_sync.py", + "description": "Sample for GetIamPolicy", + "file": "compute_v1_generated_network_firewall_policies_get_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkFirewallPolicies_AddRule_sync", + "regionTag": "compute_v1_generated_NetworkFirewallPolicies_GetIamPolicy_sync", "segments": [ { "end": 52, @@ -26329,7 +27457,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_firewall_policies_add_rule_sync.py" + "title": "compute_v1_generated_network_firewall_policies_get_iam_policy_sync.py" }, { "canonical": true, @@ -26338,19 +27466,19 @@ "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", "shortName": "NetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.clone_rules", + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.get_rule", "method": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.CloneRules", + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.GetRule", "service": { "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", "shortName": "NetworkFirewallPolicies" }, - "shortName": "CloneRules" + "shortName": "GetRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.CloneRulesNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1.types.GetRuleNetworkFirewallPolicyRequest" }, { "name": "project", @@ -26373,14 +27501,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "clone_rules" + "resultType": "google.cloud.compute_v1.types.FirewallPolicyRule", + "shortName": "get_rule" }, - "description": "Sample for CloneRules", - "file": "compute_v1_generated_network_firewall_policies_clone_rules_sync.py", + "description": "Sample for GetRule", + "file": "compute_v1_generated_network_firewall_policies_get_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkFirewallPolicies_CloneRules_sync", + "regionTag": "compute_v1_generated_NetworkFirewallPolicies_GetRule_sync", "segments": [ { "end": 52, @@ -26413,7 +27541,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_firewall_policies_clone_rules_sync.py" + "title": "compute_v1_generated_network_firewall_policies_get_rule_sync.py" }, { "canonical": true, @@ -26422,19 +27550,19 @@ "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", "shortName": "NetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.delete", + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.get", "method": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.Delete", + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.Get", "service": { "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", "shortName": "NetworkFirewallPolicies" }, - "shortName": "Delete" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1.types.GetNetworkFirewallPolicyRequest" }, { "name": "project", @@ -26457,14 +27585,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "resultType": "google.cloud.compute_v1.types.FirewallPolicy", + "shortName": "get" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_network_firewall_policies_delete_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_network_firewall_policies_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkFirewallPolicies_Delete_sync", + "regionTag": "compute_v1_generated_NetworkFirewallPolicies_Get_sync", "segments": [ { "end": 52, @@ -26497,7 +27625,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_firewall_policies_delete_sync.py" + "title": "compute_v1_generated_network_firewall_policies_get_sync.py" }, { "canonical": true, @@ -26506,26 +27634,106 @@ "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", "shortName": "NetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.get_association", + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.insert", "method": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.GetAssociation", + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.Insert", "service": { "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", "shortName": "NetworkFirewallPolicies" }, - "shortName": "GetAssociation" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetAssociationNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1.types.InsertNetworkFirewallPolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "firewall_policy", + "name": "firewall_policy_resource", + "type": "google.cloud.compute_v1.types.FirewallPolicy" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" + }, + "description": "Sample for Insert", + "file": "compute_v1_generated_network_firewall_policies_insert_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_NetworkFirewallPolicies_Insert_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_network_firewall_policies_insert_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", + "shortName": "NetworkFirewallPoliciesClient" + }, + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.list", + "method": { + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.List", + "service": { + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", + "shortName": "NetworkFirewallPolicies" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ListNetworkFirewallPoliciesRequest" + }, + { + "name": "project", "type": "str" }, { @@ -26541,14 +27749,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.FirewallPolicyAssociation", - "shortName": "get_association" + "resultType": "google.cloud.compute_v1.services.network_firewall_policies.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for GetAssociation", - "file": "compute_v1_generated_network_firewall_policies_get_association_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_network_firewall_policies_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkFirewallPolicies_GetAssociation_sync", + "regionTag": "compute_v1_generated_NetworkFirewallPolicies_List_sync", "segments": [ { "end": 52, @@ -26566,22 +27774,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_firewall_policies_get_association_sync.py" + "title": "compute_v1_generated_network_firewall_policies_list_sync.py" }, { "canonical": true, @@ -26590,28 +27798,32 @@ "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", "shortName": "NetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.get_iam_policy", + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.patch_rule", "method": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.GetIamPolicy", + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.PatchRule", "service": { "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", "shortName": "NetworkFirewallPolicies" }, - "shortName": "GetIamPolicy" + "shortName": "PatchRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetIamPolicyNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1.types.PatchRuleNetworkFirewallPolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "resource", + "name": "firewall_policy", "type": "str" }, + { + "name": "firewall_policy_rule_resource", + "type": "google.cloud.compute_v1.types.FirewallPolicyRule" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -26625,14 +27837,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "get_iam_policy" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "patch_rule" }, - "description": "Sample for GetIamPolicy", - "file": "compute_v1_generated_network_firewall_policies_get_iam_policy_sync.py", + "description": "Sample for PatchRule", + "file": "compute_v1_generated_network_firewall_policies_patch_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkFirewallPolicies_GetIamPolicy_sync", + "regionTag": "compute_v1_generated_NetworkFirewallPolicies_PatchRule_sync", "segments": [ { "end": 52, @@ -26665,7 +27877,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_firewall_policies_get_iam_policy_sync.py" + "title": "compute_v1_generated_network_firewall_policies_patch_rule_sync.py" }, { "canonical": true, @@ -26674,19 +27886,19 @@ "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", "shortName": "NetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.get_rule", + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.patch", "method": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.GetRule", + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.Patch", "service": { "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", "shortName": "NetworkFirewallPolicies" }, - "shortName": "GetRule" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetRuleNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1.types.PatchNetworkFirewallPolicyRequest" }, { "name": "project", @@ -26696,6 +27908,10 @@ "name": "firewall_policy", "type": "str" }, + { + "name": "firewall_policy_resource", + "type": "google.cloud.compute_v1.types.FirewallPolicy" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -26709,14 +27925,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.FirewallPolicyRule", - "shortName": "get_rule" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "patch" }, - "description": "Sample for GetRule", - "file": "compute_v1_generated_network_firewall_policies_get_rule_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_network_firewall_policies_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkFirewallPolicies_GetRule_sync", + "regionTag": "compute_v1_generated_NetworkFirewallPolicies_Patch_sync", "segments": [ { "end": 52, @@ -26749,7 +27965,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_firewall_policies_get_rule_sync.py" + "title": "compute_v1_generated_network_firewall_policies_patch_sync.py" }, { "canonical": true, @@ -26758,19 +27974,19 @@ "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", "shortName": "NetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.get", + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.remove_association", "method": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.Get", + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.RemoveAssociation", "service": { "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", "shortName": "NetworkFirewallPolicies" }, - "shortName": "Get" + "shortName": "RemoveAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1.types.RemoveAssociationNetworkFirewallPolicyRequest" }, { "name": "project", @@ -26793,14 +28009,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.FirewallPolicy", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "remove_association" }, - "description": "Sample for Get", - "file": "compute_v1_generated_network_firewall_policies_get_sync.py", + "description": "Sample for RemoveAssociation", + "file": "compute_v1_generated_network_firewall_policies_remove_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkFirewallPolicies_Get_sync", + "regionTag": "compute_v1_generated_NetworkFirewallPolicies_RemoveAssociation_sync", "segments": [ { "end": 52, @@ -26833,7 +28049,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_firewall_policies_get_sync.py" + "title": "compute_v1_generated_network_firewall_policies_remove_association_sync.py" }, { "canonical": true, @@ -26842,27 +28058,27 @@ "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", "shortName": "NetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.insert", + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.remove_rule", "method": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.Insert", + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.RemoveRule", "service": { "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", "shortName": "NetworkFirewallPolicies" }, - "shortName": "Insert" + "shortName": "RemoveRule" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1.types.RemoveRuleNetworkFirewallPolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "firewall_policy_resource", - "type": "google.cloud.compute_v1.types.FirewallPolicy" + "name": "firewall_policy", + "type": "str" }, { "name": "retry", @@ -26878,21 +28094,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "shortName": "remove_rule" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_network_firewall_policies_insert_sync.py", + "description": "Sample for RemoveRule", + "file": "compute_v1_generated_network_firewall_policies_remove_rule_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkFirewallPolicies_Insert_sync", + "regionTag": "compute_v1_generated_NetworkFirewallPolicies_RemoveRule_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -26902,22 +28118,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_firewall_policies_insert_sync.py" + "title": "compute_v1_generated_network_firewall_policies_remove_rule_sync.py" }, { "canonical": true, @@ -26926,24 +28142,32 @@ "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", "shortName": "NetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.list", + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.set_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.List", + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.SetIamPolicy", "service": { "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", "shortName": "NetworkFirewallPolicies" }, - "shortName": "List" + "shortName": "SetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListNetworkFirewallPoliciesRequest" + "type": "google.cloud.compute_v1.types.SetIamPolicyNetworkFirewallPolicyRequest" }, { "name": "project", "type": "str" }, + { + "name": "resource", + "type": "str" + }, + { + "name": "global_set_policy_request_resource", + "type": "google.cloud.compute_v1.types.GlobalSetPolicyRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -26957,14 +28181,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.network_firewall_policies.pagers.ListPager", - "shortName": "list" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "set_iam_policy" }, - "description": "Sample for List", - "file": "compute_v1_generated_network_firewall_policies_list_sync.py", + "description": "Sample for SetIamPolicy", + "file": "compute_v1_generated_network_firewall_policies_set_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkFirewallPolicies_List_sync", + "regionTag": "compute_v1_generated_NetworkFirewallPolicies_SetIamPolicy_sync", "segments": [ { "end": 52, @@ -26982,22 +28206,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_firewall_policies_list_sync.py" + "title": "compute_v1_generated_network_firewall_policies_set_iam_policy_sync.py" }, { "canonical": true, @@ -27006,31 +28230,31 @@ "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", "shortName": "NetworkFirewallPoliciesClient" }, - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.patch_rule", + "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.test_iam_permissions", "method": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.PatchRule", + "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.TestIamPermissions", "service": { "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", "shortName": "NetworkFirewallPolicies" }, - "shortName": "PatchRule" + "shortName": "TestIamPermissions" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchRuleNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1.types.TestIamPermissionsNetworkFirewallPolicyRequest" }, { "name": "project", "type": "str" }, { - "name": "firewall_policy", + "name": "resource", "type": "str" }, { - "name": "firewall_policy_rule_resource", - "type": "google.cloud.compute_v1.types.FirewallPolicyRule" + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1.types.TestPermissionsRequest" }, { "name": "retry", @@ -27045,14 +28269,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch_rule" + "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" }, - "description": "Sample for PatchRule", - "file": "compute_v1_generated_network_firewall_policies_patch_rule_sync.py", + "description": "Sample for TestIamPermissions", + "file": "compute_v1_generated_network_firewall_policies_test_iam_permissions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkFirewallPolicies_PatchRule_sync", + "regionTag": "compute_v1_generated_NetworkFirewallPolicies_TestIamPermissions_sync", "segments": [ { "end": 52, @@ -27085,40 +28309,40 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_firewall_policies_patch_rule_sync.py" + "title": "compute_v1_generated_network_firewall_policies_test_iam_permissions_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", - "shortName": "NetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1.NetworksClient", + "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.patch", + "fullName": "google.cloud.compute_v1.NetworksClient.add_peering", "method": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.Patch", + "fullName": "google.cloud.compute.v1.Networks.AddPeering", "service": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", - "shortName": "NetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1.Networks", + "shortName": "Networks" }, - "shortName": "Patch" + "shortName": "AddPeering" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1.types.AddPeeringNetworkRequest" }, { "name": "project", "type": "str" }, { - "name": "firewall_policy", + "name": "network", "type": "str" }, { - "name": "firewall_policy_resource", - "type": "google.cloud.compute_v1.types.FirewallPolicy" + "name": "networks_add_peering_request_resource", + "type": "google.cloud.compute_v1.types.NetworksAddPeeringRequest" }, { "name": "retry", @@ -27134,13 +28358,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "shortName": "add_peering" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_network_firewall_policies_patch_sync.py", + "description": "Sample for AddPeering", + "file": "compute_v1_generated_networks_add_peering_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkFirewallPolicies_Patch_sync", + "regionTag": "compute_v1_generated_Networks_AddPeering_sync", "segments": [ { "end": 52, @@ -27173,35 +28397,35 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_firewall_policies_patch_sync.py" + "title": "compute_v1_generated_networks_add_peering_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", - "shortName": "NetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1.NetworksClient", + "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.remove_association", + "fullName": "google.cloud.compute_v1.NetworksClient.delete", "method": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.RemoveAssociation", + "fullName": "google.cloud.compute.v1.Networks.Delete", "service": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", - "shortName": "NetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1.Networks", + "shortName": "Networks" }, - "shortName": "RemoveAssociation" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.RemoveAssociationNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1.types.DeleteNetworkRequest" }, { "name": "project", "type": "str" }, { - "name": "firewall_policy", + "name": "network", "type": "str" }, { @@ -27218,13 +28442,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "remove_association" + "shortName": "delete" }, - "description": "Sample for RemoveAssociation", - "file": "compute_v1_generated_network_firewall_policies_remove_association_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_networks_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkFirewallPolicies_RemoveAssociation_sync", + "regionTag": "compute_v1_generated_Networks_Delete_sync", "segments": [ { "end": 52, @@ -27257,35 +28481,35 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_firewall_policies_remove_association_sync.py" + "title": "compute_v1_generated_networks_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", - "shortName": "NetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1.NetworksClient", + "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.remove_rule", + "fullName": "google.cloud.compute_v1.NetworksClient.get_effective_firewalls", "method": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.RemoveRule", + "fullName": "google.cloud.compute.v1.Networks.GetEffectiveFirewalls", "service": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", - "shortName": "NetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1.Networks", + "shortName": "Networks" }, - "shortName": "RemoveRule" + "shortName": "GetEffectiveFirewalls" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.RemoveRuleNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1.types.GetEffectiveFirewallsNetworkRequest" }, { "name": "project", "type": "str" }, { - "name": "firewall_policy", + "name": "network", "type": "str" }, { @@ -27301,14 +28525,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "remove_rule" + "resultType": "google.cloud.compute_v1.types.NetworksGetEffectiveFirewallsResponse", + "shortName": "get_effective_firewalls" }, - "description": "Sample for RemoveRule", - "file": "compute_v1_generated_network_firewall_policies_remove_rule_sync.py", + "description": "Sample for GetEffectiveFirewalls", + "file": "compute_v1_generated_networks_get_effective_firewalls_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkFirewallPolicies_RemoveRule_sync", + "regionTag": "compute_v1_generated_Networks_GetEffectiveFirewalls_sync", "segments": [ { "end": 52, @@ -27341,41 +28565,37 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_firewall_policies_remove_rule_sync.py" + "title": "compute_v1_generated_networks_get_effective_firewalls_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", - "shortName": "NetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1.NetworksClient", + "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.set_iam_policy", + "fullName": "google.cloud.compute_v1.NetworksClient.get", "method": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.SetIamPolicy", + "fullName": "google.cloud.compute.v1.Networks.Get", "service": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", - "shortName": "NetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1.Networks", + "shortName": "Networks" }, - "shortName": "SetIamPolicy" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetIamPolicyNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1.types.GetNetworkRequest" }, { "name": "project", "type": "str" }, { - "name": "resource", + "name": "network", "type": "str" }, - { - "name": "global_set_policy_request_resource", - "type": "google.cloud.compute_v1.types.GlobalSetPolicyRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -27389,14 +28609,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "set_iam_policy" + "resultType": "google.cloud.compute_v1.types.Network", + "shortName": "get" }, - "description": "Sample for SetIamPolicy", - "file": "compute_v1_generated_network_firewall_policies_set_iam_policy_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_networks_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkFirewallPolicies_SetIamPolicy_sync", + "regionTag": "compute_v1_generated_Networks_Get_sync", "segments": [ { "end": 52, @@ -27429,40 +28649,36 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_firewall_policies_set_iam_policy_sync.py" + "title": "compute_v1_generated_networks_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient", - "shortName": "NetworkFirewallPoliciesClient" + "fullName": "google.cloud.compute_v1.NetworksClient", + "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworkFirewallPoliciesClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1.NetworksClient.insert", "method": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies.TestIamPermissions", + "fullName": "google.cloud.compute.v1.Networks.Insert", "service": { - "fullName": "google.cloud.compute.v1.NetworkFirewallPolicies", - "shortName": "NetworkFirewallPolicies" + "fullName": "google.cloud.compute.v1.Networks", + "shortName": "Networks" }, - "shortName": "TestIamPermissions" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.TestIamPermissionsNetworkFirewallPolicyRequest" + "type": "google.cloud.compute_v1.types.InsertNetworkRequest" }, { "name": "project", "type": "str" }, { - "name": "resource", - "type": "str" - }, - { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + "name": "network_resource", + "type": "google.cloud.compute_v1.types.Network" }, { "name": "retry", @@ -27477,22 +28693,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1_generated_network_firewall_policies_test_iam_permissions_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_networks_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NetworkFirewallPolicies_TestIamPermissions_sync", + "regionTag": "compute_v1_generated_Networks_Insert_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -27502,22 +28718,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_network_firewall_policies_test_iam_permissions_sync.py" + "title": "compute_v1_generated_networks_insert_sync.py" }, { "canonical": true, @@ -27526,19 +28742,19 @@ "fullName": "google.cloud.compute_v1.NetworksClient", "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.add_peering", + "fullName": "google.cloud.compute_v1.NetworksClient.list_peering_routes", "method": { - "fullName": "google.cloud.compute.v1.Networks.AddPeering", + "fullName": "google.cloud.compute.v1.Networks.ListPeeringRoutes", "service": { "fullName": "google.cloud.compute.v1.Networks", "shortName": "Networks" }, - "shortName": "AddPeering" + "shortName": "ListPeeringRoutes" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AddPeeringNetworkRequest" + "type": "google.cloud.compute_v1.types.ListPeeringRoutesNetworksRequest" }, { "name": "project", @@ -27548,10 +28764,6 @@ "name": "network", "type": "str" }, - { - "name": "networks_add_peering_request_resource", - "type": "google.cloud.compute_v1.types.NetworksAddPeeringRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -27565,22 +28777,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "add_peering" + "resultType": "google.cloud.compute_v1.services.networks.pagers.ListPeeringRoutesPager", + "shortName": "list_peering_routes" }, - "description": "Sample for AddPeering", - "file": "compute_v1_generated_networks_add_peering_sync.py", + "description": "Sample for ListPeeringRoutes", + "file": "compute_v1_generated_networks_list_peering_routes_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_AddPeering_sync", + "regionTag": "compute_v1_generated_Networks_ListPeeringRoutes_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -27600,12 +28812,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 54, "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_add_peering_sync.py" + "title": "compute_v1_generated_networks_list_peering_routes_sync.py" }, { "canonical": true, @@ -27614,28 +28826,24 @@ "fullName": "google.cloud.compute_v1.NetworksClient", "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.delete", + "fullName": "google.cloud.compute_v1.NetworksClient.list", "method": { - "fullName": "google.cloud.compute.v1.Networks.Delete", + "fullName": "google.cloud.compute.v1.Networks.List", "service": { "fullName": "google.cloud.compute.v1.Networks", "shortName": "Networks" }, - "shortName": "Delete" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteNetworkRequest" + "type": "google.cloud.compute_v1.types.ListNetworksRequest" }, { "name": "project", "type": "str" }, - { - "name": "network", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -27649,14 +28857,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "resultType": "google.cloud.compute_v1.services.networks.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_networks_delete_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_networks_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_Delete_sync", + "regionTag": "compute_v1_generated_Networks_List_sync", "segments": [ { "end": 52, @@ -27674,22 +28882,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_delete_sync.py" + "title": "compute_v1_generated_networks_list_sync.py" }, { "canonical": true, @@ -27698,19 +28906,19 @@ "fullName": "google.cloud.compute_v1.NetworksClient", "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.get_effective_firewalls", + "fullName": "google.cloud.compute_v1.NetworksClient.patch", "method": { - "fullName": "google.cloud.compute.v1.Networks.GetEffectiveFirewalls", + "fullName": "google.cloud.compute.v1.Networks.Patch", "service": { "fullName": "google.cloud.compute.v1.Networks", "shortName": "Networks" }, - "shortName": "GetEffectiveFirewalls" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetEffectiveFirewallsNetworkRequest" + "type": "google.cloud.compute_v1.types.PatchNetworkRequest" }, { "name": "project", @@ -27720,6 +28928,10 @@ "name": "network", "type": "str" }, + { + "name": "network_resource", + "type": "google.cloud.compute_v1.types.Network" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -27733,14 +28945,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.NetworksGetEffectiveFirewallsResponse", - "shortName": "get_effective_firewalls" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "patch" }, - "description": "Sample for GetEffectiveFirewalls", - "file": "compute_v1_generated_networks_get_effective_firewalls_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_networks_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_GetEffectiveFirewalls_sync", + "regionTag": "compute_v1_generated_Networks_Patch_sync", "segments": [ { "end": 52, @@ -27773,7 +28985,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_get_effective_firewalls_sync.py" + "title": "compute_v1_generated_networks_patch_sync.py" }, { "canonical": true, @@ -27782,19 +28994,19 @@ "fullName": "google.cloud.compute_v1.NetworksClient", "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.get", + "fullName": "google.cloud.compute_v1.NetworksClient.remove_peering", "method": { - "fullName": "google.cloud.compute.v1.Networks.Get", + "fullName": "google.cloud.compute.v1.Networks.RemovePeering", "service": { "fullName": "google.cloud.compute.v1.Networks", "shortName": "Networks" }, - "shortName": "Get" + "shortName": "RemovePeering" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetNetworkRequest" + "type": "google.cloud.compute_v1.types.RemovePeeringNetworkRequest" }, { "name": "project", @@ -27804,6 +29016,10 @@ "name": "network", "type": "str" }, + { + "name": "networks_remove_peering_request_resource", + "type": "google.cloud.compute_v1.types.NetworksRemovePeeringRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -27817,14 +29033,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Network", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "remove_peering" }, - "description": "Sample for Get", - "file": "compute_v1_generated_networks_get_sync.py", + "description": "Sample for RemovePeering", + "file": "compute_v1_generated_networks_remove_peering_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_Get_sync", + "regionTag": "compute_v1_generated_Networks_RemovePeering_sync", "segments": [ { "end": 52, @@ -27857,7 +29073,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_get_sync.py" + "title": "compute_v1_generated_networks_remove_peering_sync.py" }, { "canonical": true, @@ -27866,27 +29082,27 @@ "fullName": "google.cloud.compute_v1.NetworksClient", "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.insert", + "fullName": "google.cloud.compute_v1.NetworksClient.switch_to_custom_mode", "method": { - "fullName": "google.cloud.compute.v1.Networks.Insert", + "fullName": "google.cloud.compute.v1.Networks.SwitchToCustomMode", "service": { "fullName": "google.cloud.compute.v1.Networks", "shortName": "Networks" }, - "shortName": "Insert" + "shortName": "SwitchToCustomMode" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertNetworkRequest" + "type": "google.cloud.compute_v1.types.SwitchToCustomModeNetworkRequest" }, { "name": "project", "type": "str" }, { - "name": "network_resource", - "type": "google.cloud.compute_v1.types.Network" + "name": "network", + "type": "str" }, { "name": "retry", @@ -27902,21 +29118,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "shortName": "switch_to_custom_mode" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_networks_insert_sync.py", + "description": "Sample for SwitchToCustomMode", + "file": "compute_v1_generated_networks_switch_to_custom_mode_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_Insert_sync", + "regionTag": "compute_v1_generated_Networks_SwitchToCustomMode_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -27926,22 +29142,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_insert_sync.py" + "title": "compute_v1_generated_networks_switch_to_custom_mode_sync.py" }, { "canonical": true, @@ -27950,19 +29166,19 @@ "fullName": "google.cloud.compute_v1.NetworksClient", "shortName": "NetworksClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.list_peering_routes", + "fullName": "google.cloud.compute_v1.NetworksClient.update_peering", "method": { - "fullName": "google.cloud.compute.v1.Networks.ListPeeringRoutes", + "fullName": "google.cloud.compute.v1.Networks.UpdatePeering", "service": { "fullName": "google.cloud.compute.v1.Networks", "shortName": "Networks" }, - "shortName": "ListPeeringRoutes" + "shortName": "UpdatePeering" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListPeeringRoutesNetworksRequest" + "type": "google.cloud.compute_v1.types.UpdatePeeringNetworkRequest" }, { "name": "project", @@ -27972,6 +29188,10 @@ "name": "network", "type": "str" }, + { + "name": "networks_update_peering_request_resource", + "type": "google.cloud.compute_v1.types.NetworksUpdatePeeringRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -27985,22 +29205,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.networks.pagers.ListPeeringRoutesPager", - "shortName": "list_peering_routes" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "update_peering" }, - "description": "Sample for ListPeeringRoutes", - "file": "compute_v1_generated_networks_list_peering_routes_sync.py", + "description": "Sample for UpdatePeering", + "file": "compute_v1_generated_networks_update_peering_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_ListPeeringRoutes_sync", + "regionTag": "compute_v1_generated_Networks_UpdatePeering_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -28020,38 +29240,50 @@ "type": "REQUEST_EXECUTION" }, { - "end": 54, + "end": 53, "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_list_peering_routes_sync.py" + "title": "compute_v1_generated_networks_update_peering_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworksClient", - "shortName": "NetworksClient" + "fullName": "google.cloud.compute_v1.NodeGroupsClient", + "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.list", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.add_nodes", "method": { - "fullName": "google.cloud.compute.v1.Networks.List", + "fullName": "google.cloud.compute.v1.NodeGroups.AddNodes", "service": { - "fullName": "google.cloud.compute.v1.Networks", - "shortName": "Networks" + "fullName": "google.cloud.compute.v1.NodeGroups", + "shortName": "NodeGroups" }, - "shortName": "List" + "shortName": "AddNodes" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListNetworksRequest" + "type": "google.cloud.compute_v1.types.AddNodesNodeGroupRequest" }, { "name": "project", "type": "str" }, + { + "name": "zone", + "type": "str" + }, + { + "name": "node_group", + "type": "str" + }, + { + "name": "node_groups_add_nodes_request_resource", + "type": "google.cloud.compute_v1.types.NodeGroupsAddNodesRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -28065,22 +29297,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.networks.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "add_nodes" }, - "description": "Sample for List", - "file": "compute_v1_generated_networks_list_sync.py", + "description": "Sample for AddNodes", + "file": "compute_v1_generated_node_groups_add_nodes_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_List_sync", + "regionTag": "compute_v1_generated_NodeGroups_AddNodes_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -28090,56 +29322,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_list_sync.py" + "title": "compute_v1_generated_node_groups_add_nodes_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworksClient", - "shortName": "NetworksClient" + "fullName": "google.cloud.compute_v1.NodeGroupsClient", + "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.patch", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1.Networks.Patch", + "fullName": "google.cloud.compute.v1.NodeGroups.AggregatedList", "service": { - "fullName": "google.cloud.compute.v1.Networks", - "shortName": "Networks" + "fullName": "google.cloud.compute.v1.NodeGroups", + "shortName": "NodeGroups" }, - "shortName": "Patch" + "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchNetworkRequest" + "type": "google.cloud.compute_v1.types.AggregatedListNodeGroupsRequest" }, { "name": "project", "type": "str" }, - { - "name": "network", - "type": "str" - }, - { - "name": "network_resource", - "type": "google.cloud.compute_v1.types.Network" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -28153,14 +29377,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "resultType": "google.cloud.compute_v1.services.node_groups.pagers.AggregatedListPager", + "shortName": "aggregated_list" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_networks_patch_sync.py", + "description": "Sample for AggregatedList", + "file": "compute_v1_generated_node_groups_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_Patch_sync", + "regionTag": "compute_v1_generated_NodeGroups_AggregatedList_sync", "segments": [ { "end": 52, @@ -28178,55 +29402,59 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_patch_sync.py" + "title": "compute_v1_generated_node_groups_aggregated_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworksClient", - "shortName": "NetworksClient" + "fullName": "google.cloud.compute_v1.NodeGroupsClient", + "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.remove_peering", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.delete_nodes", "method": { - "fullName": "google.cloud.compute.v1.Networks.RemovePeering", + "fullName": "google.cloud.compute.v1.NodeGroups.DeleteNodes", "service": { - "fullName": "google.cloud.compute.v1.Networks", - "shortName": "Networks" + "fullName": "google.cloud.compute.v1.NodeGroups", + "shortName": "NodeGroups" }, - "shortName": "RemovePeering" + "shortName": "DeleteNodes" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.RemovePeeringNetworkRequest" + "type": "google.cloud.compute_v1.types.DeleteNodesNodeGroupRequest" }, { "name": "project", "type": "str" }, { - "name": "network", + "name": "zone", "type": "str" }, { - "name": "networks_remove_peering_request_resource", - "type": "google.cloud.compute_v1.types.NetworksRemovePeeringRequest" + "name": "node_group", + "type": "str" + }, + { + "name": "node_groups_delete_nodes_request_resource", + "type": "google.cloud.compute_v1.types.NodeGroupsDeleteNodesRequest" }, { "name": "retry", @@ -28242,21 +29470,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "remove_peering" + "shortName": "delete_nodes" }, - "description": "Sample for RemovePeering", - "file": "compute_v1_generated_networks_remove_peering_sync.py", + "description": "Sample for DeleteNodes", + "file": "compute_v1_generated_node_groups_delete_nodes_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_RemovePeering_sync", + "regionTag": "compute_v1_generated_NodeGroups_DeleteNodes_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -28266,50 +29494,54 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_remove_peering_sync.py" + "title": "compute_v1_generated_node_groups_delete_nodes_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworksClient", - "shortName": "NetworksClient" + "fullName": "google.cloud.compute_v1.NodeGroupsClient", + "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.switch_to_custom_mode", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.delete", "method": { - "fullName": "google.cloud.compute.v1.Networks.SwitchToCustomMode", + "fullName": "google.cloud.compute.v1.NodeGroups.Delete", "service": { - "fullName": "google.cloud.compute.v1.Networks", - "shortName": "Networks" + "fullName": "google.cloud.compute.v1.NodeGroups", + "shortName": "NodeGroups" }, - "shortName": "SwitchToCustomMode" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SwitchToCustomModeNetworkRequest" + "type": "google.cloud.compute_v1.types.DeleteNodeGroupRequest" }, { "name": "project", "type": "str" }, { - "name": "network", + "name": "zone", + "type": "str" + }, + { + "name": "node_group", "type": "str" }, { @@ -28326,21 +29558,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "switch_to_custom_mode" + "shortName": "delete" }, - "description": "Sample for SwitchToCustomMode", - "file": "compute_v1_generated_networks_switch_to_custom_mode_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_node_groups_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_SwitchToCustomMode_sync", + "regionTag": "compute_v1_generated_NodeGroups_Delete_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -28350,55 +29582,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_switch_to_custom_mode_sync.py" + "title": "compute_v1_generated_node_groups_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NetworksClient", - "shortName": "NetworksClient" + "fullName": "google.cloud.compute_v1.NodeGroupsClient", + "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NetworksClient.update_peering", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.get_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.Networks.UpdatePeering", + "fullName": "google.cloud.compute.v1.NodeGroups.GetIamPolicy", "service": { - "fullName": "google.cloud.compute.v1.Networks", - "shortName": "Networks" + "fullName": "google.cloud.compute.v1.NodeGroups", + "shortName": "NodeGroups" }, - "shortName": "UpdatePeering" + "shortName": "GetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.UpdatePeeringNetworkRequest" + "type": "google.cloud.compute_v1.types.GetIamPolicyNodeGroupRequest" }, { "name": "project", "type": "str" }, { - "name": "network", + "name": "zone", "type": "str" }, { - "name": "networks_update_peering_request_resource", - "type": "google.cloud.compute_v1.types.NetworksUpdatePeeringRequest" + "name": "resource", + "type": "str" }, { "name": "retry", @@ -28413,22 +29645,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "update_peering" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "get_iam_policy" }, - "description": "Sample for UpdatePeering", - "file": "compute_v1_generated_networks_update_peering_sync.py", + "description": "Sample for GetIamPolicy", + "file": "compute_v1_generated_node_groups_get_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Networks_UpdatePeering_sync", + "regionTag": "compute_v1_generated_NodeGroups_GetIamPolicy_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -28438,22 +29670,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_networks_update_peering_sync.py" + "title": "compute_v1_generated_node_groups_get_iam_policy_sync.py" }, { "canonical": true, @@ -28462,19 +29694,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.add_nodes", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.get", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.AddNodes", + "fullName": "google.cloud.compute.v1.NodeGroups.Get", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "AddNodes" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AddNodesNodeGroupRequest" + "type": "google.cloud.compute_v1.types.GetNodeGroupRequest" }, { "name": "project", @@ -28488,10 +29720,6 @@ "name": "node_group", "type": "str" }, - { - "name": "node_groups_add_nodes_request_resource", - "type": "google.cloud.compute_v1.types.NodeGroupsAddNodesRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -28505,14 +29733,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "add_nodes" + "resultType": "google.cloud.compute_v1.types.NodeGroup", + "shortName": "get" }, - "description": "Sample for AddNodes", - "file": "compute_v1_generated_node_groups_add_nodes_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_node_groups_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_AddNodes_sync", + "regionTag": "compute_v1_generated_NodeGroups_Get_sync", "segments": [ { "end": 53, @@ -28545,7 +29773,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_add_nodes_sync.py" + "title": "compute_v1_generated_node_groups_get_sync.py" }, { "canonical": true, @@ -28554,24 +29782,36 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.aggregated_list", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.insert", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.AggregatedList", + "fullName": "google.cloud.compute.v1.NodeGroups.Insert", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "AggregatedList" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AggregatedListNodeGroupsRequest" + "type": "google.cloud.compute_v1.types.InsertNodeGroupRequest" }, { "name": "project", "type": "str" }, + { + "name": "zone", + "type": "str" + }, + { + "name": "initial_node_count", + "type": "int" + }, + { + "name": "node_group_resource", + "type": "google.cloud.compute_v1.types.NodeGroup" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -28585,22 +29825,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.node_groups.pagers.AggregatedListPager", - "shortName": "aggregated_list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" }, - "description": "Sample for AggregatedList", - "file": "compute_v1_generated_node_groups_aggregated_list_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_node_groups_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_AggregatedList_sync", + "regionTag": "compute_v1_generated_NodeGroups_Insert_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -28610,22 +29850,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_aggregated_list_sync.py" + "title": "compute_v1_generated_node_groups_insert_sync.py" }, { "canonical": true, @@ -28634,19 +29874,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.delete_nodes", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.list_nodes", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.DeleteNodes", + "fullName": "google.cloud.compute.v1.NodeGroups.ListNodes", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "DeleteNodes" + "shortName": "ListNodes" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteNodesNodeGroupRequest" + "type": "google.cloud.compute_v1.types.ListNodesNodeGroupsRequest" }, { "name": "project", @@ -28660,10 +29900,6 @@ "name": "node_group", "type": "str" }, - { - "name": "node_groups_delete_nodes_request_resource", - "type": "google.cloud.compute_v1.types.NodeGroupsDeleteNodesRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -28677,22 +29913,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete_nodes" + "resultType": "google.cloud.compute_v1.services.node_groups.pagers.ListNodesPager", + "shortName": "list_nodes" }, - "description": "Sample for DeleteNodes", - "file": "compute_v1_generated_node_groups_delete_nodes_sync.py", + "description": "Sample for ListNodes", + "file": "compute_v1_generated_node_groups_list_nodes_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_DeleteNodes_sync", + "regionTag": "compute_v1_generated_NodeGroups_ListNodes_sync", "segments": [ { - "end": 53, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 54, "start": 27, "type": "SHORT" }, @@ -28712,12 +29948,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 54, + "end": 55, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_delete_nodes_sync.py" + "title": "compute_v1_generated_node_groups_list_nodes_sync.py" }, { "canonical": true, @@ -28726,19 +29962,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.delete", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.list", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.Delete", + "fullName": "google.cloud.compute.v1.NodeGroups.List", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "Delete" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteNodeGroupRequest" + "type": "google.cloud.compute_v1.types.ListNodeGroupsRequest" }, { "name": "project", @@ -28748,10 +29984,6 @@ "name": "zone", "type": "str" }, - { - "name": "node_group", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -28765,14 +29997,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "resultType": "google.cloud.compute_v1.services.node_groups.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_node_groups_delete_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_node_groups_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_Delete_sync", + "regionTag": "compute_v1_generated_NodeGroups_List_sync", "segments": [ { "end": 53, @@ -28790,22 +30022,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 51, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_delete_sync.py" + "title": "compute_v1_generated_node_groups_list_sync.py" }, { "canonical": true, @@ -28814,19 +30046,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.get_iam_policy", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.patch", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.GetIamPolicy", + "fullName": "google.cloud.compute.v1.NodeGroups.Patch", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "GetIamPolicy" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetIamPolicyNodeGroupRequest" + "type": "google.cloud.compute_v1.types.PatchNodeGroupRequest" }, { "name": "project", @@ -28837,9 +30069,13 @@ "type": "str" }, { - "name": "resource", + "name": "node_group", "type": "str" }, + { + "name": "node_group_resource", + "type": "google.cloud.compute_v1.types.NodeGroup" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -28853,14 +30089,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "get_iam_policy" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "patch" }, - "description": "Sample for GetIamPolicy", - "file": "compute_v1_generated_node_groups_get_iam_policy_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_node_groups_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_GetIamPolicy_sync", + "regionTag": "compute_v1_generated_NodeGroups_Patch_sync", "segments": [ { "end": 53, @@ -28893,7 +30129,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_get_iam_policy_sync.py" + "title": "compute_v1_generated_node_groups_patch_sync.py" }, { "canonical": true, @@ -28902,19 +30138,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.get", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.set_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.Get", + "fullName": "google.cloud.compute.v1.NodeGroups.SetIamPolicy", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "Get" + "shortName": "SetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetNodeGroupRequest" + "type": "google.cloud.compute_v1.types.SetIamPolicyNodeGroupRequest" }, { "name": "project", @@ -28925,9 +30161,13 @@ "type": "str" }, { - "name": "node_group", + "name": "resource", "type": "str" }, + { + "name": "zone_set_policy_request_resource", + "type": "google.cloud.compute_v1.types.ZoneSetPolicyRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -28941,14 +30181,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.NodeGroup", - "shortName": "get" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "set_iam_policy" }, - "description": "Sample for Get", - "file": "compute_v1_generated_node_groups_get_sync.py", + "description": "Sample for SetIamPolicy", + "file": "compute_v1_generated_node_groups_set_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_Get_sync", + "regionTag": "compute_v1_generated_NodeGroups_SetIamPolicy_sync", "segments": [ { "end": 53, @@ -28981,7 +30221,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_get_sync.py" + "title": "compute_v1_generated_node_groups_set_iam_policy_sync.py" }, { "canonical": true, @@ -28990,19 +30230,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.insert", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.set_node_template", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.Insert", + "fullName": "google.cloud.compute.v1.NodeGroups.SetNodeTemplate", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "Insert" + "shortName": "SetNodeTemplate" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertNodeGroupRequest" + "type": "google.cloud.compute_v1.types.SetNodeTemplateNodeGroupRequest" }, { "name": "project", @@ -29013,12 +30253,12 @@ "type": "str" }, { - "name": "initial_node_count", - "type": "int" + "name": "node_group", + "type": "str" }, { - "name": "node_group_resource", - "type": "google.cloud.compute_v1.types.NodeGroup" + "name": "node_groups_set_node_template_request_resource", + "type": "google.cloud.compute_v1.types.NodeGroupsSetNodeTemplateRequest" }, { "name": "retry", @@ -29034,13 +30274,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "shortName": "set_node_template" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_node_groups_insert_sync.py", + "description": "Sample for SetNodeTemplate", + "file": "compute_v1_generated_node_groups_set_node_template_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_Insert_sync", + "regionTag": "compute_v1_generated_NodeGroups_SetNodeTemplate_sync", "segments": [ { "end": 53, @@ -29073,7 +30313,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_insert_sync.py" + "title": "compute_v1_generated_node_groups_set_node_template_sync.py" }, { "canonical": true, @@ -29082,19 +30322,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.list_nodes", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.simulate_maintenance_event", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.ListNodes", + "fullName": "google.cloud.compute.v1.NodeGroups.SimulateMaintenanceEvent", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "ListNodes" + "shortName": "SimulateMaintenanceEvent" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListNodesNodeGroupsRequest" + "type": "google.cloud.compute_v1.types.SimulateMaintenanceEventNodeGroupRequest" }, { "name": "project", @@ -29108,6 +30348,10 @@ "name": "node_group", "type": "str" }, + { + "name": "node_groups_simulate_maintenance_event_request_resource", + "type": "google.cloud.compute_v1.types.NodeGroupsSimulateMaintenanceEventRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -29121,22 +30365,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.node_groups.pagers.ListNodesPager", - "shortName": "list_nodes" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "simulate_maintenance_event" }, - "description": "Sample for ListNodes", - "file": "compute_v1_generated_node_groups_list_nodes_sync.py", + "description": "Sample for SimulateMaintenanceEvent", + "file": "compute_v1_generated_node_groups_simulate_maintenance_event_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_ListNodes_sync", + "regionTag": "compute_v1_generated_NodeGroups_SimulateMaintenanceEvent_sync", "segments": [ { - "end": 54, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 53, "start": 27, "type": "SHORT" }, @@ -29156,12 +30400,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 55, + "end": 54, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_list_nodes_sync.py" + "title": "compute_v1_generated_node_groups_simulate_maintenance_event_sync.py" }, { "canonical": true, @@ -29170,19 +30414,19 @@ "fullName": "google.cloud.compute_v1.NodeGroupsClient", "shortName": "NodeGroupsClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.list", + "fullName": "google.cloud.compute_v1.NodeGroupsClient.test_iam_permissions", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.List", + "fullName": "google.cloud.compute.v1.NodeGroups.TestIamPermissions", "service": { "fullName": "google.cloud.compute.v1.NodeGroups", "shortName": "NodeGroups" }, - "shortName": "List" + "shortName": "TestIamPermissions" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListNodeGroupsRequest" + "type": "google.cloud.compute_v1.types.TestIamPermissionsNodeGroupRequest" }, { "name": "project", @@ -29192,6 +30436,14 @@ "name": "zone", "type": "str" }, + { + "name": "resource", + "type": "str" + }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -29205,14 +30457,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.node_groups.pagers.ListPager", - "shortName": "list" + "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" }, - "description": "Sample for List", - "file": "compute_v1_generated_node_groups_list_sync.py", + "description": "Sample for TestIamPermissions", + "file": "compute_v1_generated_node_groups_test_iam_permissions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_List_sync", + "regionTag": "compute_v1_generated_NodeGroups_TestIamPermissions_sync", "segments": [ { "end": 53, @@ -29230,60 +30482,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 50, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_list_sync.py" + "title": "compute_v1_generated_node_groups_test_iam_permissions_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NodeGroupsClient", - "shortName": "NodeGroupsClient" + "fullName": "google.cloud.compute_v1.NodeTemplatesClient", + "shortName": "NodeTemplatesClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.patch", + "fullName": "google.cloud.compute_v1.NodeTemplatesClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.Patch", + "fullName": "google.cloud.compute.v1.NodeTemplates.AggregatedList", "service": { - "fullName": "google.cloud.compute.v1.NodeGroups", - "shortName": "NodeGroups" + "fullName": "google.cloud.compute.v1.NodeTemplates", + "shortName": "NodeTemplates" }, - "shortName": "Patch" + "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchNodeGroupRequest" + "type": "google.cloud.compute_v1.types.AggregatedListNodeTemplatesRequest" }, { "name": "project", "type": "str" }, - { - "name": "zone", - "type": "str" - }, - { - "name": "node_group", - "type": "str" - }, - { - "name": "node_group_resource", - "type": "google.cloud.compute_v1.types.NodeGroup" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -29297,22 +30537,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "resultType": "google.cloud.compute_v1.services.node_templates.pagers.AggregatedListPager", + "shortName": "aggregated_list" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_node_groups_patch_sync.py", + "description": "Sample for AggregatedList", + "file": "compute_v1_generated_node_templates_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_Patch_sync", + "regionTag": "compute_v1_generated_NodeTemplates_AggregatedList_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -29322,60 +30562,56 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_patch_sync.py" + "title": "compute_v1_generated_node_templates_aggregated_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NodeGroupsClient", - "shortName": "NodeGroupsClient" + "fullName": "google.cloud.compute_v1.NodeTemplatesClient", + "shortName": "NodeTemplatesClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.set_iam_policy", + "fullName": "google.cloud.compute_v1.NodeTemplatesClient.delete", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.SetIamPolicy", + "fullName": "google.cloud.compute.v1.NodeTemplates.Delete", "service": { - "fullName": "google.cloud.compute.v1.NodeGroups", - "shortName": "NodeGroups" + "fullName": "google.cloud.compute.v1.NodeTemplates", + "shortName": "NodeTemplates" }, - "shortName": "SetIamPolicy" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetIamPolicyNodeGroupRequest" + "type": "google.cloud.compute_v1.types.DeleteNodeTemplateRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", + "name": "region", "type": "str" }, { - "name": "resource", + "name": "node_template", "type": "str" }, - { - "name": "zone_set_policy_request_resource", - "type": "google.cloud.compute_v1.types.ZoneSetPolicyRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -29389,14 +30625,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "set_iam_policy" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for SetIamPolicy", - "file": "compute_v1_generated_node_groups_set_iam_policy_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_node_templates_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_SetIamPolicy_sync", + "regionTag": "compute_v1_generated_NodeTemplates_Delete_sync", "segments": [ { "end": 53, @@ -29429,45 +30665,41 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_set_iam_policy_sync.py" + "title": "compute_v1_generated_node_templates_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NodeGroupsClient", - "shortName": "NodeGroupsClient" + "fullName": "google.cloud.compute_v1.NodeTemplatesClient", + "shortName": "NodeTemplatesClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.set_node_template", + "fullName": "google.cloud.compute_v1.NodeTemplatesClient.get_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.SetNodeTemplate", + "fullName": "google.cloud.compute.v1.NodeTemplates.GetIamPolicy", "service": { - "fullName": "google.cloud.compute.v1.NodeGroups", - "shortName": "NodeGroups" + "fullName": "google.cloud.compute.v1.NodeTemplates", + "shortName": "NodeTemplates" }, - "shortName": "SetNodeTemplate" + "shortName": "GetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetNodeTemplateNodeGroupRequest" + "type": "google.cloud.compute_v1.types.GetIamPolicyNodeTemplateRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", + "name": "region", "type": "str" }, { - "name": "node_group", + "name": "resource", "type": "str" }, - { - "name": "node_groups_set_node_template_request_resource", - "type": "google.cloud.compute_v1.types.NodeGroupsSetNodeTemplateRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -29481,14 +30713,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_node_template" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "get_iam_policy" }, - "description": "Sample for SetNodeTemplate", - "file": "compute_v1_generated_node_groups_set_node_template_sync.py", + "description": "Sample for GetIamPolicy", + "file": "compute_v1_generated_node_templates_get_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_SetNodeTemplate_sync", + "regionTag": "compute_v1_generated_NodeTemplates_GetIamPolicy_sync", "segments": [ { "end": 53, @@ -29521,45 +30753,41 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_set_node_template_sync.py" + "title": "compute_v1_generated_node_templates_get_iam_policy_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NodeGroupsClient", - "shortName": "NodeGroupsClient" + "fullName": "google.cloud.compute_v1.NodeTemplatesClient", + "shortName": "NodeTemplatesClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.simulate_maintenance_event", + "fullName": "google.cloud.compute_v1.NodeTemplatesClient.get", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.SimulateMaintenanceEvent", + "fullName": "google.cloud.compute.v1.NodeTemplates.Get", "service": { - "fullName": "google.cloud.compute.v1.NodeGroups", - "shortName": "NodeGroups" + "fullName": "google.cloud.compute.v1.NodeTemplates", + "shortName": "NodeTemplates" }, - "shortName": "SimulateMaintenanceEvent" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SimulateMaintenanceEventNodeGroupRequest" + "type": "google.cloud.compute_v1.types.GetNodeTemplateRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", + "name": "region", "type": "str" }, { - "name": "node_group", + "name": "node_template", "type": "str" }, - { - "name": "node_groups_simulate_maintenance_event_request_resource", - "type": "google.cloud.compute_v1.types.NodeGroupsSimulateMaintenanceEventRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -29573,14 +30801,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "simulate_maintenance_event" + "resultType": "google.cloud.compute_v1.types.NodeTemplate", + "shortName": "get" }, - "description": "Sample for SimulateMaintenanceEvent", - "file": "compute_v1_generated_node_groups_simulate_maintenance_event_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_node_templates_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_SimulateMaintenanceEvent_sync", + "regionTag": "compute_v1_generated_NodeTemplates_Get_sync", "segments": [ { "end": 53, @@ -29613,44 +30841,40 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_simulate_maintenance_event_sync.py" + "title": "compute_v1_generated_node_templates_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NodeGroupsClient", - "shortName": "NodeGroupsClient" + "fullName": "google.cloud.compute_v1.NodeTemplatesClient", + "shortName": "NodeTemplatesClient" }, - "fullName": "google.cloud.compute_v1.NodeGroupsClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1.NodeTemplatesClient.insert", "method": { - "fullName": "google.cloud.compute.v1.NodeGroups.TestIamPermissions", + "fullName": "google.cloud.compute.v1.NodeTemplates.Insert", "service": { - "fullName": "google.cloud.compute.v1.NodeGroups", - "shortName": "NodeGroups" + "fullName": "google.cloud.compute.v1.NodeTemplates", + "shortName": "NodeTemplates" }, - "shortName": "TestIamPermissions" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.TestIamPermissionsNodeGroupRequest" + "type": "google.cloud.compute_v1.types.InsertNodeTemplateRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", - "type": "str" - }, - { - "name": "resource", + "name": "region", "type": "str" }, { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + "name": "node_template_resource", + "type": "google.cloud.compute_v1.types.NodeTemplate" }, { "name": "retry", @@ -29665,22 +30889,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1_generated_node_groups_test_iam_permissions_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_node_templates_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeGroups_TestIamPermissions_sync", + "regionTag": "compute_v1_generated_NodeTemplates_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -29690,22 +30914,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_groups_test_iam_permissions_sync.py" + "title": "compute_v1_generated_node_templates_insert_sync.py" }, { "canonical": true, @@ -29714,24 +30938,28 @@ "fullName": "google.cloud.compute_v1.NodeTemplatesClient", "shortName": "NodeTemplatesClient" }, - "fullName": "google.cloud.compute_v1.NodeTemplatesClient.aggregated_list", + "fullName": "google.cloud.compute_v1.NodeTemplatesClient.list", "method": { - "fullName": "google.cloud.compute.v1.NodeTemplates.AggregatedList", + "fullName": "google.cloud.compute.v1.NodeTemplates.List", "service": { "fullName": "google.cloud.compute.v1.NodeTemplates", "shortName": "NodeTemplates" }, - "shortName": "AggregatedList" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AggregatedListNodeTemplatesRequest" + "type": "google.cloud.compute_v1.types.ListNodeTemplatesRequest" }, { "name": "project", "type": "str" }, + { + "name": "region", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -29745,22 +30973,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.node_templates.pagers.AggregatedListPager", - "shortName": "aggregated_list" + "resultType": "google.cloud.compute_v1.services.node_templates.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for AggregatedList", - "file": "compute_v1_generated_node_templates_aggregated_list_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_node_templates_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeTemplates_AggregatedList_sync", + "regionTag": "compute_v1_generated_NodeTemplates_List_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -29770,22 +30998,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 54, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_templates_aggregated_list_sync.py" + "title": "compute_v1_generated_node_templates_list_sync.py" }, { "canonical": true, @@ -29794,19 +31022,19 @@ "fullName": "google.cloud.compute_v1.NodeTemplatesClient", "shortName": "NodeTemplatesClient" }, - "fullName": "google.cloud.compute_v1.NodeTemplatesClient.delete", + "fullName": "google.cloud.compute_v1.NodeTemplatesClient.set_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.NodeTemplates.Delete", + "fullName": "google.cloud.compute.v1.NodeTemplates.SetIamPolicy", "service": { "fullName": "google.cloud.compute.v1.NodeTemplates", "shortName": "NodeTemplates" }, - "shortName": "Delete" + "shortName": "SetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteNodeTemplateRequest" + "type": "google.cloud.compute_v1.types.SetIamPolicyNodeTemplateRequest" }, { "name": "project", @@ -29817,9 +31045,13 @@ "type": "str" }, { - "name": "node_template", + "name": "resource", "type": "str" }, + { + "name": "region_set_policy_request_resource", + "type": "google.cloud.compute_v1.types.RegionSetPolicyRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -29833,14 +31065,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "set_iam_policy" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_node_templates_delete_sync.py", + "description": "Sample for SetIamPolicy", + "file": "compute_v1_generated_node_templates_set_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeTemplates_Delete_sync", + "regionTag": "compute_v1_generated_NodeTemplates_SetIamPolicy_sync", "segments": [ { "end": 53, @@ -29873,7 +31105,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_templates_delete_sync.py" + "title": "compute_v1_generated_node_templates_set_iam_policy_sync.py" }, { "canonical": true, @@ -29882,19 +31114,19 @@ "fullName": "google.cloud.compute_v1.NodeTemplatesClient", "shortName": "NodeTemplatesClient" }, - "fullName": "google.cloud.compute_v1.NodeTemplatesClient.get_iam_policy", + "fullName": "google.cloud.compute_v1.NodeTemplatesClient.test_iam_permissions", "method": { - "fullName": "google.cloud.compute.v1.NodeTemplates.GetIamPolicy", + "fullName": "google.cloud.compute.v1.NodeTemplates.TestIamPermissions", "service": { "fullName": "google.cloud.compute.v1.NodeTemplates", "shortName": "NodeTemplates" }, - "shortName": "GetIamPolicy" + "shortName": "TestIamPermissions" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetIamPolicyNodeTemplateRequest" + "type": "google.cloud.compute_v1.types.TestIamPermissionsNodeTemplateRequest" }, { "name": "project", @@ -29908,6 +31140,10 @@ "name": "resource", "type": "str" }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -29921,14 +31157,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "get_iam_policy" + "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" }, - "description": "Sample for GetIamPolicy", - "file": "compute_v1_generated_node_templates_get_iam_policy_sync.py", + "description": "Sample for TestIamPermissions", + "file": "compute_v1_generated_node_templates_test_iam_permissions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeTemplates_GetIamPolicy_sync", + "regionTag": "compute_v1_generated_NodeTemplates_TestIamPermissions_sync", "segments": [ { "end": 53, @@ -29961,41 +31197,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_templates_get_iam_policy_sync.py" + "title": "compute_v1_generated_node_templates_test_iam_permissions_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NodeTemplatesClient", - "shortName": "NodeTemplatesClient" + "fullName": "google.cloud.compute_v1.NodeTypesClient", + "shortName": "NodeTypesClient" }, - "fullName": "google.cloud.compute_v1.NodeTemplatesClient.get", + "fullName": "google.cloud.compute_v1.NodeTypesClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1.NodeTemplates.Get", + "fullName": "google.cloud.compute.v1.NodeTypes.AggregatedList", "service": { - "fullName": "google.cloud.compute.v1.NodeTemplates", - "shortName": "NodeTemplates" + "fullName": "google.cloud.compute.v1.NodeTypes", + "shortName": "NodeTypes" }, - "shortName": "Get" + "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetNodeTemplateRequest" + "type": "google.cloud.compute_v1.types.AggregatedListNodeTypesRequest" }, { "name": "project", "type": "str" }, - { - "name": "region", - "type": "str" - }, - { - "name": "node_template", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -30009,22 +31237,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.NodeTemplate", - "shortName": "get" + "resultType": "google.cloud.compute_v1.services.node_types.pagers.AggregatedListPager", + "shortName": "aggregated_list" }, - "description": "Sample for Get", - "file": "compute_v1_generated_node_templates_get_sync.py", + "description": "Sample for AggregatedList", + "file": "compute_v1_generated_node_types_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeTemplates_Get_sync", + "regionTag": "compute_v1_generated_NodeTypes_AggregatedList_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -30034,55 +31262,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_templates_get_sync.py" + "title": "compute_v1_generated_node_types_aggregated_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NodeTemplatesClient", - "shortName": "NodeTemplatesClient" + "fullName": "google.cloud.compute_v1.NodeTypesClient", + "shortName": "NodeTypesClient" }, - "fullName": "google.cloud.compute_v1.NodeTemplatesClient.insert", + "fullName": "google.cloud.compute_v1.NodeTypesClient.get", "method": { - "fullName": "google.cloud.compute.v1.NodeTemplates.Insert", + "fullName": "google.cloud.compute.v1.NodeTypes.Get", "service": { - "fullName": "google.cloud.compute.v1.NodeTemplates", - "shortName": "NodeTemplates" + "fullName": "google.cloud.compute.v1.NodeTypes", + "shortName": "NodeTypes" }, - "shortName": "Insert" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertNodeTemplateRequest" + "type": "google.cloud.compute_v1.types.GetNodeTypeRequest" }, { "name": "project", "type": "str" }, { - "name": "region", + "name": "zone", "type": "str" }, { - "name": "node_template_resource", - "type": "google.cloud.compute_v1.types.NodeTemplate" + "name": "node_type", + "type": "str" }, { "name": "retry", @@ -30097,22 +31325,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "resultType": "google.cloud.compute_v1.types.NodeType", + "shortName": "get" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_node_templates_insert_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_node_types_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeTemplates_Insert_sync", + "regionTag": "compute_v1_generated_NodeTypes_Get_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -30122,50 +31350,50 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_templates_insert_sync.py" + "title": "compute_v1_generated_node_types_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NodeTemplatesClient", - "shortName": "NodeTemplatesClient" + "fullName": "google.cloud.compute_v1.NodeTypesClient", + "shortName": "NodeTypesClient" }, - "fullName": "google.cloud.compute_v1.NodeTemplatesClient.list", + "fullName": "google.cloud.compute_v1.NodeTypesClient.list", "method": { - "fullName": "google.cloud.compute.v1.NodeTemplates.List", + "fullName": "google.cloud.compute.v1.NodeTypes.List", "service": { - "fullName": "google.cloud.compute.v1.NodeTemplates", - "shortName": "NodeTemplates" + "fullName": "google.cloud.compute.v1.NodeTypes", + "shortName": "NodeTypes" }, "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListNodeTemplatesRequest" + "type": "google.cloud.compute_v1.types.ListNodeTypesRequest" }, { "name": "project", "type": "str" }, { - "name": "region", + "name": "zone", "type": "str" }, { @@ -30181,14 +31409,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.node_templates.pagers.ListPager", + "resultType": "google.cloud.compute_v1.services.node_types.pagers.ListPager", "shortName": "list" }, "description": "Sample for List", - "file": "compute_v1_generated_node_templates_list_sync.py", + "file": "compute_v1_generated_node_types_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeTemplates_List_sync", + "regionTag": "compute_v1_generated_NodeTypes_List_sync", "segments": [ { "end": 53, @@ -30221,45 +31449,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_templates_list_sync.py" + "title": "compute_v1_generated_node_types_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NodeTemplatesClient", - "shortName": "NodeTemplatesClient" + "fullName": "google.cloud.compute_v1.PacketMirroringsClient", + "shortName": "PacketMirroringsClient" }, - "fullName": "google.cloud.compute_v1.NodeTemplatesClient.set_iam_policy", + "fullName": "google.cloud.compute_v1.PacketMirroringsClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1.NodeTemplates.SetIamPolicy", + "fullName": "google.cloud.compute.v1.PacketMirrorings.AggregatedList", "service": { - "fullName": "google.cloud.compute.v1.NodeTemplates", - "shortName": "NodeTemplates" + "fullName": "google.cloud.compute.v1.PacketMirrorings", + "shortName": "PacketMirrorings" }, - "shortName": "SetIamPolicy" + "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetIamPolicyNodeTemplateRequest" + "type": "google.cloud.compute_v1.types.AggregatedListPacketMirroringsRequest" }, { "name": "project", "type": "str" }, - { - "name": "region", - "type": "str" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "region_set_policy_request_resource", - "type": "google.cloud.compute_v1.types.RegionSetPolicyRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -30273,22 +31489,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "set_iam_policy" + "resultType": "google.cloud.compute_v1.services.packet_mirrorings.pagers.AggregatedListPager", + "shortName": "aggregated_list" }, - "description": "Sample for SetIamPolicy", - "file": "compute_v1_generated_node_templates_set_iam_policy_sync.py", + "description": "Sample for AggregatedList", + "file": "compute_v1_generated_packet_mirrorings_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeTemplates_SetIamPolicy_sync", + "regionTag": "compute_v1_generated_PacketMirrorings_AggregatedList_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -30298,43 +31514,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_templates_set_iam_policy_sync.py" + "title": "compute_v1_generated_packet_mirrorings_aggregated_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NodeTemplatesClient", - "shortName": "NodeTemplatesClient" + "fullName": "google.cloud.compute_v1.PacketMirroringsClient", + "shortName": "PacketMirroringsClient" }, - "fullName": "google.cloud.compute_v1.NodeTemplatesClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1.PacketMirroringsClient.delete", "method": { - "fullName": "google.cloud.compute.v1.NodeTemplates.TestIamPermissions", + "fullName": "google.cloud.compute.v1.PacketMirrorings.Delete", "service": { - "fullName": "google.cloud.compute.v1.NodeTemplates", - "shortName": "NodeTemplates" + "fullName": "google.cloud.compute.v1.PacketMirrorings", + "shortName": "PacketMirrorings" }, - "shortName": "TestIamPermissions" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.TestIamPermissionsNodeTemplateRequest" + "type": "google.cloud.compute_v1.types.DeletePacketMirroringRequest" }, { "name": "project", @@ -30345,13 +31561,9 @@ "type": "str" }, { - "name": "resource", + "name": "packet_mirroring", "type": "str" }, - { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1.types.TestPermissionsRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -30365,14 +31577,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1_generated_node_templates_test_iam_permissions_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_packet_mirrorings_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeTemplates_TestIamPermissions_sync", + "regionTag": "compute_v1_generated_PacketMirrorings_Delete_sync", "segments": [ { "end": 53, @@ -30405,33 +31617,41 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_templates_test_iam_permissions_sync.py" + "title": "compute_v1_generated_packet_mirrorings_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NodeTypesClient", - "shortName": "NodeTypesClient" + "fullName": "google.cloud.compute_v1.PacketMirroringsClient", + "shortName": "PacketMirroringsClient" }, - "fullName": "google.cloud.compute_v1.NodeTypesClient.aggregated_list", + "fullName": "google.cloud.compute_v1.PacketMirroringsClient.get", "method": { - "fullName": "google.cloud.compute.v1.NodeTypes.AggregatedList", + "fullName": "google.cloud.compute.v1.PacketMirrorings.Get", "service": { - "fullName": "google.cloud.compute.v1.NodeTypes", - "shortName": "NodeTypes" + "fullName": "google.cloud.compute.v1.PacketMirrorings", + "shortName": "PacketMirrorings" }, - "shortName": "AggregatedList" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AggregatedListNodeTypesRequest" + "type": "google.cloud.compute_v1.types.GetPacketMirroringRequest" }, { "name": "project", "type": "str" }, + { + "name": "region", + "type": "str" + }, + { + "name": "packet_mirroring", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -30445,22 +31665,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.node_types.pagers.AggregatedListPager", - "shortName": "aggregated_list" + "resultType": "google.cloud.compute_v1.types.PacketMirroring", + "shortName": "get" }, - "description": "Sample for AggregatedList", - "file": "compute_v1_generated_node_types_aggregated_list_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_packet_mirrorings_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeTypes_AggregatedList_sync", + "regionTag": "compute_v1_generated_PacketMirrorings_Get_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -30470,55 +31690,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_types_aggregated_list_sync.py" + "title": "compute_v1_generated_packet_mirrorings_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NodeTypesClient", - "shortName": "NodeTypesClient" + "fullName": "google.cloud.compute_v1.PacketMirroringsClient", + "shortName": "PacketMirroringsClient" }, - "fullName": "google.cloud.compute_v1.NodeTypesClient.get", + "fullName": "google.cloud.compute_v1.PacketMirroringsClient.insert", "method": { - "fullName": "google.cloud.compute.v1.NodeTypes.Get", + "fullName": "google.cloud.compute.v1.PacketMirrorings.Insert", "service": { - "fullName": "google.cloud.compute.v1.NodeTypes", - "shortName": "NodeTypes" + "fullName": "google.cloud.compute.v1.PacketMirrorings", + "shortName": "PacketMirrorings" }, - "shortName": "Get" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetNodeTypeRequest" + "type": "google.cloud.compute_v1.types.InsertPacketMirroringRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", + "name": "region", "type": "str" }, { - "name": "node_type", - "type": "str" + "name": "packet_mirroring_resource", + "type": "google.cloud.compute_v1.types.PacketMirroring" }, { "name": "retry", @@ -30533,22 +31753,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.NodeType", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" }, - "description": "Sample for Get", - "file": "compute_v1_generated_node_types_get_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_packet_mirrorings_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeTypes_Get_sync", + "regionTag": "compute_v1_generated_PacketMirrorings_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -30558,50 +31778,50 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_types_get_sync.py" + "title": "compute_v1_generated_packet_mirrorings_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.NodeTypesClient", - "shortName": "NodeTypesClient" + "fullName": "google.cloud.compute_v1.PacketMirroringsClient", + "shortName": "PacketMirroringsClient" }, - "fullName": "google.cloud.compute_v1.NodeTypesClient.list", + "fullName": "google.cloud.compute_v1.PacketMirroringsClient.list", "method": { - "fullName": "google.cloud.compute.v1.NodeTypes.List", + "fullName": "google.cloud.compute.v1.PacketMirrorings.List", "service": { - "fullName": "google.cloud.compute.v1.NodeTypes", - "shortName": "NodeTypes" + "fullName": "google.cloud.compute.v1.PacketMirrorings", + "shortName": "PacketMirrorings" }, "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListNodeTypesRequest" + "type": "google.cloud.compute_v1.types.ListPacketMirroringsRequest" }, { "name": "project", "type": "str" }, { - "name": "zone", + "name": "region", "type": "str" }, { @@ -30617,14 +31837,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.node_types.pagers.ListPager", + "resultType": "google.cloud.compute_v1.services.packet_mirrorings.pagers.ListPager", "shortName": "list" }, "description": "Sample for List", - "file": "compute_v1_generated_node_types_list_sync.py", + "file": "compute_v1_generated_packet_mirrorings_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_NodeTypes_List_sync", + "regionTag": "compute_v1_generated_PacketMirrorings_List_sync", "segments": [ { "end": 53, @@ -30657,7 +31877,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_node_types_list_sync.py" + "title": "compute_v1_generated_packet_mirrorings_list_sync.py" }, { "canonical": true, @@ -30666,24 +31886,36 @@ "fullName": "google.cloud.compute_v1.PacketMirroringsClient", "shortName": "PacketMirroringsClient" }, - "fullName": "google.cloud.compute_v1.PacketMirroringsClient.aggregated_list", + "fullName": "google.cloud.compute_v1.PacketMirroringsClient.patch", "method": { - "fullName": "google.cloud.compute.v1.PacketMirrorings.AggregatedList", + "fullName": "google.cloud.compute.v1.PacketMirrorings.Patch", "service": { "fullName": "google.cloud.compute.v1.PacketMirrorings", "shortName": "PacketMirrorings" }, - "shortName": "AggregatedList" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AggregatedListPacketMirroringsRequest" + "type": "google.cloud.compute_v1.types.PatchPacketMirroringRequest" }, { "name": "project", "type": "str" }, + { + "name": "region", + "type": "str" + }, + { + "name": "packet_mirroring", + "type": "str" + }, + { + "name": "packet_mirroring_resource", + "type": "google.cloud.compute_v1.types.PacketMirroring" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -30697,22 +31929,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.packet_mirrorings.pagers.AggregatedListPager", - "shortName": "aggregated_list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "patch" }, - "description": "Sample for AggregatedList", - "file": "compute_v1_generated_packet_mirrorings_aggregated_list_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_packet_mirrorings_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PacketMirrorings_AggregatedList_sync", + "regionTag": "compute_v1_generated_PacketMirrorings_Patch_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -30722,22 +31954,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_packet_mirrorings_aggregated_list_sync.py" + "title": "compute_v1_generated_packet_mirrorings_patch_sync.py" }, { "canonical": true, @@ -30746,19 +31978,19 @@ "fullName": "google.cloud.compute_v1.PacketMirroringsClient", "shortName": "PacketMirroringsClient" }, - "fullName": "google.cloud.compute_v1.PacketMirroringsClient.delete", + "fullName": "google.cloud.compute_v1.PacketMirroringsClient.test_iam_permissions", "method": { - "fullName": "google.cloud.compute.v1.PacketMirrorings.Delete", + "fullName": "google.cloud.compute.v1.PacketMirrorings.TestIamPermissions", "service": { "fullName": "google.cloud.compute.v1.PacketMirrorings", "shortName": "PacketMirrorings" }, - "shortName": "Delete" + "shortName": "TestIamPermissions" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeletePacketMirroringRequest" + "type": "google.cloud.compute_v1.types.TestIamPermissionsPacketMirroringRequest" }, { "name": "project", @@ -30769,9 +32001,13 @@ "type": "str" }, { - "name": "packet_mirroring", + "name": "resource", "type": "str" }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -30785,14 +32021,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_packet_mirrorings_delete_sync.py", + "description": "Sample for TestIamPermissions", + "file": "compute_v1_generated_packet_mirrorings_test_iam_permissions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PacketMirrorings_Delete_sync", + "regionTag": "compute_v1_generated_PacketMirrorings_TestIamPermissions_sync", "segments": [ { "end": 53, @@ -30825,41 +32061,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_packet_mirrorings_delete_sync.py" + "title": "compute_v1_generated_packet_mirrorings_test_iam_permissions_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PacketMirroringsClient", - "shortName": "PacketMirroringsClient" + "fullName": "google.cloud.compute_v1.ProjectsClient", + "shortName": "ProjectsClient" }, - "fullName": "google.cloud.compute_v1.PacketMirroringsClient.get", + "fullName": "google.cloud.compute_v1.ProjectsClient.disable_xpn_host", "method": { - "fullName": "google.cloud.compute.v1.PacketMirrorings.Get", + "fullName": "google.cloud.compute.v1.Projects.DisableXpnHost", "service": { - "fullName": "google.cloud.compute.v1.PacketMirrorings", - "shortName": "PacketMirrorings" + "fullName": "google.cloud.compute.v1.Projects", + "shortName": "Projects" }, - "shortName": "Get" + "shortName": "DisableXpnHost" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetPacketMirroringRequest" + "type": "google.cloud.compute_v1.types.DisableXpnHostProjectRequest" }, { "name": "project", "type": "str" }, - { - "name": "region", - "type": "str" - }, - { - "name": "packet_mirroring", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -30873,22 +32101,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.PacketMirroring", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "disable_xpn_host" }, - "description": "Sample for Get", - "file": "compute_v1_generated_packet_mirrorings_get_sync.py", + "description": "Sample for DisableXpnHost", + "file": "compute_v1_generated_projects_disable_xpn_host_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PacketMirrorings_Get_sync", + "regionTag": "compute_v1_generated_Projects_DisableXpnHost_sync", "segments": [ { - "end": 53, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 51, "start": 27, "type": "SHORT" }, @@ -30898,55 +32126,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_packet_mirrorings_get_sync.py" + "title": "compute_v1_generated_projects_disable_xpn_host_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PacketMirroringsClient", - "shortName": "PacketMirroringsClient" + "fullName": "google.cloud.compute_v1.ProjectsClient", + "shortName": "ProjectsClient" }, - "fullName": "google.cloud.compute_v1.PacketMirroringsClient.insert", + "fullName": "google.cloud.compute_v1.ProjectsClient.disable_xpn_resource", "method": { - "fullName": "google.cloud.compute.v1.PacketMirrorings.Insert", + "fullName": "google.cloud.compute.v1.Projects.DisableXpnResource", "service": { - "fullName": "google.cloud.compute.v1.PacketMirrorings", - "shortName": "PacketMirrorings" + "fullName": "google.cloud.compute.v1.Projects", + "shortName": "Projects" }, - "shortName": "Insert" + "shortName": "DisableXpnResource" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertPacketMirroringRequest" + "type": "google.cloud.compute_v1.types.DisableXpnResourceProjectRequest" }, { "name": "project", "type": "str" }, { - "name": "region", - "type": "str" - }, - { - "name": "packet_mirroring_resource", - "type": "google.cloud.compute_v1.types.PacketMirroring" + "name": "projects_disable_xpn_resource_request_resource", + "type": "google.cloud.compute_v1.types.ProjectsDisableXpnResourceRequest" }, { "name": "retry", @@ -30962,21 +32186,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "shortName": "disable_xpn_resource" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_packet_mirrorings_insert_sync.py", + "description": "Sample for DisableXpnResource", + "file": "compute_v1_generated_projects_disable_xpn_resource_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PacketMirrorings_Insert_sync", + "regionTag": "compute_v1_generated_Projects_DisableXpnResource_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -30986,52 +32210,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_packet_mirrorings_insert_sync.py" + "title": "compute_v1_generated_projects_disable_xpn_resource_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PacketMirroringsClient", - "shortName": "PacketMirroringsClient" + "fullName": "google.cloud.compute_v1.ProjectsClient", + "shortName": "ProjectsClient" }, - "fullName": "google.cloud.compute_v1.PacketMirroringsClient.list", + "fullName": "google.cloud.compute_v1.ProjectsClient.enable_xpn_host", "method": { - "fullName": "google.cloud.compute.v1.PacketMirrorings.List", + "fullName": "google.cloud.compute.v1.Projects.EnableXpnHost", "service": { - "fullName": "google.cloud.compute.v1.PacketMirrorings", - "shortName": "PacketMirrorings" + "fullName": "google.cloud.compute.v1.Projects", + "shortName": "Projects" }, - "shortName": "List" + "shortName": "EnableXpnHost" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListPacketMirroringsRequest" + "type": "google.cloud.compute_v1.types.EnableXpnHostProjectRequest" }, { "name": "project", "type": "str" }, - { - "name": "region", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -31045,22 +32265,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.packet_mirrorings.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "enable_xpn_host" }, - "description": "Sample for List", - "file": "compute_v1_generated_packet_mirrorings_list_sync.py", + "description": "Sample for EnableXpnHost", + "file": "compute_v1_generated_projects_enable_xpn_host_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PacketMirrorings_List_sync", + "regionTag": "compute_v1_generated_Projects_EnableXpnHost_sync", "segments": [ { - "end": 53, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 51, "start": 27, "type": "SHORT" }, @@ -31070,59 +32290,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_packet_mirrorings_list_sync.py" + "title": "compute_v1_generated_projects_enable_xpn_host_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PacketMirroringsClient", - "shortName": "PacketMirroringsClient" + "fullName": "google.cloud.compute_v1.ProjectsClient", + "shortName": "ProjectsClient" }, - "fullName": "google.cloud.compute_v1.PacketMirroringsClient.patch", + "fullName": "google.cloud.compute_v1.ProjectsClient.enable_xpn_resource", "method": { - "fullName": "google.cloud.compute.v1.PacketMirrorings.Patch", + "fullName": "google.cloud.compute.v1.Projects.EnableXpnResource", "service": { - "fullName": "google.cloud.compute.v1.PacketMirrorings", - "shortName": "PacketMirrorings" + "fullName": "google.cloud.compute.v1.Projects", + "shortName": "Projects" }, - "shortName": "Patch" + "shortName": "EnableXpnResource" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchPacketMirroringRequest" + "type": "google.cloud.compute_v1.types.EnableXpnResourceProjectRequest" }, { "name": "project", "type": "str" }, { - "name": "region", - "type": "str" - }, - { - "name": "packet_mirroring", - "type": "str" - }, - { - "name": "packet_mirroring_resource", - "type": "google.cloud.compute_v1.types.PacketMirroring" + "name": "projects_enable_xpn_resource_request_resource", + "type": "google.cloud.compute_v1.types.ProjectsEnableXpnResourceRequest" }, { "name": "retry", @@ -31138,21 +32350,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "shortName": "enable_xpn_resource" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_packet_mirrorings_patch_sync.py", + "description": "Sample for EnableXpnResource", + "file": "compute_v1_generated_projects_enable_xpn_resource_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PacketMirrorings_Patch_sync", + "regionTag": "compute_v1_generated_Projects_EnableXpnResource_sync", "segments": [ { - "end": 53, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 51, "start": 27, "type": "SHORT" }, @@ -31162,59 +32374,127 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_packet_mirrorings_patch_sync.py" + "title": "compute_v1_generated_projects_enable_xpn_resource_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PacketMirroringsClient", - "shortName": "PacketMirroringsClient" + "fullName": "google.cloud.compute_v1.ProjectsClient", + "shortName": "ProjectsClient" }, - "fullName": "google.cloud.compute_v1.PacketMirroringsClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1.ProjectsClient.get_xpn_host", "method": { - "fullName": "google.cloud.compute.v1.PacketMirrorings.TestIamPermissions", + "fullName": "google.cloud.compute.v1.Projects.GetXpnHost", "service": { - "fullName": "google.cloud.compute.v1.PacketMirrorings", - "shortName": "PacketMirrorings" + "fullName": "google.cloud.compute.v1.Projects", + "shortName": "Projects" }, - "shortName": "TestIamPermissions" + "shortName": "GetXpnHost" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.TestIamPermissionsPacketMirroringRequest" + "type": "google.cloud.compute_v1.types.GetXpnHostProjectRequest" }, { "name": "project", "type": "str" }, { - "name": "region", - "type": "str" + "name": "retry", + "type": "google.api_core.retry.Retry" }, { - "name": "resource", - "type": "str" + "name": "timeout", + "type": "float" }, { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.compute_v1.types.Project", + "shortName": "get_xpn_host" + }, + "description": "Sample for GetXpnHost", + "file": "compute_v1_generated_projects_get_xpn_host_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Projects_GetXpnHost_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_projects_get_xpn_host_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.ProjectsClient", + "shortName": "ProjectsClient" + }, + "fullName": "google.cloud.compute_v1.ProjectsClient.get_xpn_resources", + "method": { + "fullName": "google.cloud.compute.v1.Projects.GetXpnResources", + "service": { + "fullName": "google.cloud.compute.v1.Projects", + "shortName": "Projects" + }, + "shortName": "GetXpnResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.GetXpnResourcesProjectsRequest" + }, + { + "name": "project", + "type": "str" }, { "name": "retry", @@ -31229,22 +32509,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.cloud.compute_v1.services.projects.pagers.GetXpnResourcesPager", + "shortName": "get_xpn_resources" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1_generated_packet_mirrorings_test_iam_permissions_sync.py", + "description": "Sample for GetXpnResources", + "file": "compute_v1_generated_projects_get_xpn_resources_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PacketMirrorings_TestIamPermissions_sync", + "regionTag": "compute_v1_generated_Projects_GetXpnResources_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -31254,22 +32534,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_packet_mirrorings_test_iam_permissions_sync.py" + "title": "compute_v1_generated_projects_get_xpn_resources_sync.py" }, { "canonical": true, @@ -31278,19 +32558,19 @@ "fullName": "google.cloud.compute_v1.ProjectsClient", "shortName": "ProjectsClient" }, - "fullName": "google.cloud.compute_v1.ProjectsClient.disable_xpn_host", + "fullName": "google.cloud.compute_v1.ProjectsClient.get", "method": { - "fullName": "google.cloud.compute.v1.Projects.DisableXpnHost", + "fullName": "google.cloud.compute.v1.Projects.Get", "service": { "fullName": "google.cloud.compute.v1.Projects", "shortName": "Projects" }, - "shortName": "DisableXpnHost" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DisableXpnHostProjectRequest" + "type": "google.cloud.compute_v1.types.GetProjectRequest" }, { "name": "project", @@ -31309,14 +32589,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "disable_xpn_host" + "resultType": "google.cloud.compute_v1.types.Project", + "shortName": "get" }, - "description": "Sample for DisableXpnHost", - "file": "compute_v1_generated_projects_disable_xpn_host_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_projects_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Projects_DisableXpnHost_sync", + "regionTag": "compute_v1_generated_Projects_Get_sync", "segments": [ { "end": 51, @@ -31349,7 +32629,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_projects_disable_xpn_host_sync.py" + "title": "compute_v1_generated_projects_get_sync.py" }, { "canonical": true, @@ -31358,27 +32638,27 @@ "fullName": "google.cloud.compute_v1.ProjectsClient", "shortName": "ProjectsClient" }, - "fullName": "google.cloud.compute_v1.ProjectsClient.disable_xpn_resource", + "fullName": "google.cloud.compute_v1.ProjectsClient.list_xpn_hosts", "method": { - "fullName": "google.cloud.compute.v1.Projects.DisableXpnResource", + "fullName": "google.cloud.compute.v1.Projects.ListXpnHosts", "service": { "fullName": "google.cloud.compute.v1.Projects", "shortName": "Projects" }, - "shortName": "DisableXpnResource" + "shortName": "ListXpnHosts" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DisableXpnResourceProjectRequest" + "type": "google.cloud.compute_v1.types.ListXpnHostsProjectsRequest" }, { "name": "project", "type": "str" }, { - "name": "projects_disable_xpn_resource_request_resource", - "type": "google.cloud.compute_v1.types.ProjectsDisableXpnResourceRequest" + "name": "projects_list_xpn_hosts_request_resource", + "type": "google.cloud.compute_v1.types.ProjectsListXpnHostsRequest" }, { "name": "retry", @@ -31393,22 +32673,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "disable_xpn_resource" + "resultType": "google.cloud.compute_v1.services.projects.pagers.ListXpnHostsPager", + "shortName": "list_xpn_hosts" }, - "description": "Sample for DisableXpnResource", - "file": "compute_v1_generated_projects_disable_xpn_resource_sync.py", + "description": "Sample for ListXpnHosts", + "file": "compute_v1_generated_projects_list_xpn_hosts_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Projects_DisableXpnResource_sync", + "regionTag": "compute_v1_generated_Projects_ListXpnHosts_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -31428,12 +32708,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_projects_disable_xpn_resource_sync.py" + "title": "compute_v1_generated_projects_list_xpn_hosts_sync.py" }, { "canonical": true, @@ -31442,24 +32722,28 @@ "fullName": "google.cloud.compute_v1.ProjectsClient", "shortName": "ProjectsClient" }, - "fullName": "google.cloud.compute_v1.ProjectsClient.enable_xpn_host", + "fullName": "google.cloud.compute_v1.ProjectsClient.move_disk", "method": { - "fullName": "google.cloud.compute.v1.Projects.EnableXpnHost", + "fullName": "google.cloud.compute.v1.Projects.MoveDisk", "service": { "fullName": "google.cloud.compute.v1.Projects", "shortName": "Projects" }, - "shortName": "EnableXpnHost" + "shortName": "MoveDisk" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.EnableXpnHostProjectRequest" + "type": "google.cloud.compute_v1.types.MoveDiskProjectRequest" }, { "name": "project", "type": "str" }, + { + "name": "disk_move_request_resource", + "type": "google.cloud.compute_v1.types.DiskMoveRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -31474,13 +32758,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "enable_xpn_host" + "shortName": "move_disk" }, - "description": "Sample for EnableXpnHost", - "file": "compute_v1_generated_projects_enable_xpn_host_sync.py", + "description": "Sample for MoveDisk", + "file": "compute_v1_generated_projects_move_disk_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Projects_EnableXpnHost_sync", + "regionTag": "compute_v1_generated_Projects_MoveDisk_sync", "segments": [ { "end": 51, @@ -31513,7 +32797,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_projects_enable_xpn_host_sync.py" + "title": "compute_v1_generated_projects_move_disk_sync.py" }, { "canonical": true, @@ -31522,27 +32806,27 @@ "fullName": "google.cloud.compute_v1.ProjectsClient", "shortName": "ProjectsClient" }, - "fullName": "google.cloud.compute_v1.ProjectsClient.enable_xpn_resource", + "fullName": "google.cloud.compute_v1.ProjectsClient.move_instance", "method": { - "fullName": "google.cloud.compute.v1.Projects.EnableXpnResource", + "fullName": "google.cloud.compute.v1.Projects.MoveInstance", "service": { "fullName": "google.cloud.compute.v1.Projects", "shortName": "Projects" }, - "shortName": "EnableXpnResource" + "shortName": "MoveInstance" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.EnableXpnResourceProjectRequest" + "type": "google.cloud.compute_v1.types.MoveInstanceProjectRequest" }, { "name": "project", "type": "str" }, { - "name": "projects_enable_xpn_resource_request_resource", - "type": "google.cloud.compute_v1.types.ProjectsEnableXpnResourceRequest" + "name": "instance_move_request_resource", + "type": "google.cloud.compute_v1.types.InstanceMoveRequest" }, { "name": "retry", @@ -31558,13 +32842,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "enable_xpn_resource" + "shortName": "move_instance" }, - "description": "Sample for EnableXpnResource", - "file": "compute_v1_generated_projects_enable_xpn_resource_sync.py", + "description": "Sample for MoveInstance", + "file": "compute_v1_generated_projects_move_instance_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Projects_EnableXpnResource_sync", + "regionTag": "compute_v1_generated_Projects_MoveInstance_sync", "segments": [ { "end": 51, @@ -31597,7 +32881,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_projects_enable_xpn_resource_sync.py" + "title": "compute_v1_generated_projects_move_instance_sync.py" }, { "canonical": true, @@ -31606,24 +32890,28 @@ "fullName": "google.cloud.compute_v1.ProjectsClient", "shortName": "ProjectsClient" }, - "fullName": "google.cloud.compute_v1.ProjectsClient.get_xpn_host", + "fullName": "google.cloud.compute_v1.ProjectsClient.set_cloud_armor_tier", "method": { - "fullName": "google.cloud.compute.v1.Projects.GetXpnHost", + "fullName": "google.cloud.compute.v1.Projects.SetCloudArmorTier", "service": { "fullName": "google.cloud.compute.v1.Projects", "shortName": "Projects" }, - "shortName": "GetXpnHost" + "shortName": "SetCloudArmorTier" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetXpnHostProjectRequest" + "type": "google.cloud.compute_v1.types.SetCloudArmorTierProjectRequest" }, { "name": "project", "type": "str" }, + { + "name": "projects_set_cloud_armor_tier_request_resource", + "type": "google.cloud.compute_v1.types.ProjectsSetCloudArmorTierRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -31637,14 +32925,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Project", - "shortName": "get_xpn_host" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "set_cloud_armor_tier" }, - "description": "Sample for GetXpnHost", - "file": "compute_v1_generated_projects_get_xpn_host_sync.py", + "description": "Sample for SetCloudArmorTier", + "file": "compute_v1_generated_projects_set_cloud_armor_tier_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Projects_GetXpnHost_sync", + "regionTag": "compute_v1_generated_Projects_SetCloudArmorTier_sync", "segments": [ { "end": 51, @@ -31677,7 +32965,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_projects_get_xpn_host_sync.py" + "title": "compute_v1_generated_projects_set_cloud_armor_tier_sync.py" }, { "canonical": true, @@ -31686,24 +32974,28 @@ "fullName": "google.cloud.compute_v1.ProjectsClient", "shortName": "ProjectsClient" }, - "fullName": "google.cloud.compute_v1.ProjectsClient.get_xpn_resources", + "fullName": "google.cloud.compute_v1.ProjectsClient.set_common_instance_metadata", "method": { - "fullName": "google.cloud.compute.v1.Projects.GetXpnResources", + "fullName": "google.cloud.compute.v1.Projects.SetCommonInstanceMetadata", "service": { "fullName": "google.cloud.compute.v1.Projects", "shortName": "Projects" }, - "shortName": "GetXpnResources" + "shortName": "SetCommonInstanceMetadata" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetXpnResourcesProjectsRequest" + "type": "google.cloud.compute_v1.types.SetCommonInstanceMetadataProjectRequest" }, { "name": "project", "type": "str" }, + { + "name": "metadata_resource", + "type": "google.cloud.compute_v1.types.Metadata" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -31717,22 +33009,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.projects.pagers.GetXpnResourcesPager", - "shortName": "get_xpn_resources" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "set_common_instance_metadata" }, - "description": "Sample for GetXpnResources", - "file": "compute_v1_generated_projects_get_xpn_resources_sync.py", + "description": "Sample for SetCommonInstanceMetadata", + "file": "compute_v1_generated_projects_set_common_instance_metadata_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Projects_GetXpnResources_sync", + "regionTag": "compute_v1_generated_Projects_SetCommonInstanceMetadata_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -31752,12 +33044,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_projects_get_xpn_resources_sync.py" + "title": "compute_v1_generated_projects_set_common_instance_metadata_sync.py" }, { "canonical": true, @@ -31766,24 +33058,28 @@ "fullName": "google.cloud.compute_v1.ProjectsClient", "shortName": "ProjectsClient" }, - "fullName": "google.cloud.compute_v1.ProjectsClient.get", + "fullName": "google.cloud.compute_v1.ProjectsClient.set_default_network_tier", "method": { - "fullName": "google.cloud.compute.v1.Projects.Get", + "fullName": "google.cloud.compute.v1.Projects.SetDefaultNetworkTier", "service": { "fullName": "google.cloud.compute.v1.Projects", "shortName": "Projects" }, - "shortName": "Get" + "shortName": "SetDefaultNetworkTier" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetProjectRequest" + "type": "google.cloud.compute_v1.types.SetDefaultNetworkTierProjectRequest" }, { "name": "project", "type": "str" }, + { + "name": "projects_set_default_network_tier_request_resource", + "type": "google.cloud.compute_v1.types.ProjectsSetDefaultNetworkTierRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -31797,14 +33093,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Project", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "set_default_network_tier" }, - "description": "Sample for Get", - "file": "compute_v1_generated_projects_get_sync.py", + "description": "Sample for SetDefaultNetworkTier", + "file": "compute_v1_generated_projects_set_default_network_tier_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Projects_Get_sync", + "regionTag": "compute_v1_generated_Projects_SetDefaultNetworkTier_sync", "segments": [ { "end": 51, @@ -31837,7 +33133,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_projects_get_sync.py" + "title": "compute_v1_generated_projects_set_default_network_tier_sync.py" }, { "canonical": true, @@ -31846,27 +33142,27 @@ "fullName": "google.cloud.compute_v1.ProjectsClient", "shortName": "ProjectsClient" }, - "fullName": "google.cloud.compute_v1.ProjectsClient.list_xpn_hosts", + "fullName": "google.cloud.compute_v1.ProjectsClient.set_usage_export_bucket", "method": { - "fullName": "google.cloud.compute.v1.Projects.ListXpnHosts", + "fullName": "google.cloud.compute.v1.Projects.SetUsageExportBucket", "service": { "fullName": "google.cloud.compute.v1.Projects", "shortName": "Projects" }, - "shortName": "ListXpnHosts" + "shortName": "SetUsageExportBucket" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListXpnHostsProjectsRequest" + "type": "google.cloud.compute_v1.types.SetUsageExportBucketProjectRequest" }, { "name": "project", "type": "str" }, { - "name": "projects_list_xpn_hosts_request_resource", - "type": "google.cloud.compute_v1.types.ProjectsListXpnHostsRequest" + "name": "usage_export_location_resource", + "type": "google.cloud.compute_v1.types.UsageExportLocation" }, { "name": "retry", @@ -31881,22 +33177,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.projects.pagers.ListXpnHostsPager", - "shortName": "list_xpn_hosts" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "set_usage_export_bucket" }, - "description": "Sample for ListXpnHosts", - "file": "compute_v1_generated_projects_list_xpn_hosts_sync.py", + "description": "Sample for SetUsageExportBucket", + "file": "compute_v1_generated_projects_set_usage_export_bucket_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Projects_ListXpnHosts_sync", + "regionTag": "compute_v1_generated_Projects_SetUsageExportBucket_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -31916,41 +33212,41 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_projects_list_xpn_hosts_sync.py" + "title": "compute_v1_generated_projects_set_usage_export_bucket_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ProjectsClient", - "shortName": "ProjectsClient" + "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient", + "shortName": "PublicAdvertisedPrefixesClient" }, - "fullName": "google.cloud.compute_v1.ProjectsClient.move_disk", + "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient.announce", "method": { - "fullName": "google.cloud.compute.v1.Projects.MoveDisk", + "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes.Announce", "service": { - "fullName": "google.cloud.compute.v1.Projects", - "shortName": "Projects" + "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes", + "shortName": "PublicAdvertisedPrefixes" }, - "shortName": "MoveDisk" + "shortName": "Announce" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.MoveDiskProjectRequest" + "type": "google.cloud.compute_v1.types.AnnouncePublicAdvertisedPrefixeRequest" }, { "name": "project", "type": "str" }, { - "name": "disk_move_request_resource", - "type": "google.cloud.compute_v1.types.DiskMoveRequest" + "name": "public_advertised_prefix", + "type": "str" }, { "name": "retry", @@ -31966,21 +33262,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "move_disk" + "shortName": "announce" }, - "description": "Sample for MoveDisk", - "file": "compute_v1_generated_projects_move_disk_sync.py", + "description": "Sample for Announce", + "file": "compute_v1_generated_public_advertised_prefixes_announce_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Projects_MoveDisk_sync", + "regionTag": "compute_v1_generated_PublicAdvertisedPrefixes_Announce_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -31990,51 +33286,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_projects_move_disk_sync.py" + "title": "compute_v1_generated_public_advertised_prefixes_announce_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ProjectsClient", - "shortName": "ProjectsClient" + "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient", + "shortName": "PublicAdvertisedPrefixesClient" }, - "fullName": "google.cloud.compute_v1.ProjectsClient.move_instance", + "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient.delete", "method": { - "fullName": "google.cloud.compute.v1.Projects.MoveInstance", + "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes.Delete", "service": { - "fullName": "google.cloud.compute.v1.Projects", - "shortName": "Projects" + "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes", + "shortName": "PublicAdvertisedPrefixes" }, - "shortName": "MoveInstance" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.MoveInstanceProjectRequest" + "type": "google.cloud.compute_v1.types.DeletePublicAdvertisedPrefixeRequest" }, { "name": "project", "type": "str" }, { - "name": "instance_move_request_resource", - "type": "google.cloud.compute_v1.types.InstanceMoveRequest" + "name": "public_advertised_prefix", + "type": "str" }, { "name": "retry", @@ -32050,21 +33346,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "move_instance" + "shortName": "delete" }, - "description": "Sample for MoveInstance", - "file": "compute_v1_generated_projects_move_instance_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_public_advertised_prefixes_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Projects_MoveInstance_sync", + "regionTag": "compute_v1_generated_PublicAdvertisedPrefixes_Delete_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -32074,51 +33370,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_projects_move_instance_sync.py" + "title": "compute_v1_generated_public_advertised_prefixes_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ProjectsClient", - "shortName": "ProjectsClient" + "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient", + "shortName": "PublicAdvertisedPrefixesClient" }, - "fullName": "google.cloud.compute_v1.ProjectsClient.set_common_instance_metadata", + "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient.get", "method": { - "fullName": "google.cloud.compute.v1.Projects.SetCommonInstanceMetadata", + "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes.Get", "service": { - "fullName": "google.cloud.compute.v1.Projects", - "shortName": "Projects" + "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes", + "shortName": "PublicAdvertisedPrefixes" }, - "shortName": "SetCommonInstanceMetadata" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetCommonInstanceMetadataProjectRequest" + "type": "google.cloud.compute_v1.types.GetPublicAdvertisedPrefixeRequest" }, { "name": "project", "type": "str" }, { - "name": "metadata_resource", - "type": "google.cloud.compute_v1.types.Metadata" + "name": "public_advertised_prefix", + "type": "str" }, { "name": "retry", @@ -32133,22 +33429,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_common_instance_metadata" + "resultType": "google.cloud.compute_v1.types.PublicAdvertisedPrefix", + "shortName": "get" }, - "description": "Sample for SetCommonInstanceMetadata", - "file": "compute_v1_generated_projects_set_common_instance_metadata_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_public_advertised_prefixes_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Projects_SetCommonInstanceMetadata_sync", + "regionTag": "compute_v1_generated_PublicAdvertisedPrefixes_Get_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -32158,51 +33454,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_projects_set_common_instance_metadata_sync.py" + "title": "compute_v1_generated_public_advertised_prefixes_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ProjectsClient", - "shortName": "ProjectsClient" + "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient", + "shortName": "PublicAdvertisedPrefixesClient" }, - "fullName": "google.cloud.compute_v1.ProjectsClient.set_default_network_tier", + "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient.insert", "method": { - "fullName": "google.cloud.compute.v1.Projects.SetDefaultNetworkTier", + "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes.Insert", "service": { - "fullName": "google.cloud.compute.v1.Projects", - "shortName": "Projects" + "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes", + "shortName": "PublicAdvertisedPrefixes" }, - "shortName": "SetDefaultNetworkTier" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetDefaultNetworkTierProjectRequest" + "type": "google.cloud.compute_v1.types.InsertPublicAdvertisedPrefixeRequest" }, { "name": "project", "type": "str" }, { - "name": "projects_set_default_network_tier_request_resource", - "type": "google.cloud.compute_v1.types.ProjectsSetDefaultNetworkTierRequest" + "name": "public_advertised_prefix_resource", + "type": "google.cloud.compute_v1.types.PublicAdvertisedPrefix" }, { "name": "retry", @@ -32218,13 +33514,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_default_network_tier" + "shortName": "insert" }, - "description": "Sample for SetDefaultNetworkTier", - "file": "compute_v1_generated_projects_set_default_network_tier_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_public_advertised_prefixes_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Projects_SetDefaultNetworkTier_sync", + "regionTag": "compute_v1_generated_PublicAdvertisedPrefixes_Insert_sync", "segments": [ { "end": 51, @@ -32257,37 +33553,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_projects_set_default_network_tier_sync.py" + "title": "compute_v1_generated_public_advertised_prefixes_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.ProjectsClient", - "shortName": "ProjectsClient" + "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient", + "shortName": "PublicAdvertisedPrefixesClient" }, - "fullName": "google.cloud.compute_v1.ProjectsClient.set_usage_export_bucket", + "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient.list", "method": { - "fullName": "google.cloud.compute.v1.Projects.SetUsageExportBucket", + "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes.List", "service": { - "fullName": "google.cloud.compute.v1.Projects", - "shortName": "Projects" + "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes", + "shortName": "PublicAdvertisedPrefixes" }, - "shortName": "SetUsageExportBucket" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetUsageExportBucketProjectRequest" + "type": "google.cloud.compute_v1.types.ListPublicAdvertisedPrefixesRequest" }, { "name": "project", "type": "str" }, - { - "name": "usage_export_location_resource", - "type": "google.cloud.compute_v1.types.UsageExportLocation" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -32301,22 +33593,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_usage_export_bucket" + "resultType": "google.cloud.compute_v1.services.public_advertised_prefixes.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for SetUsageExportBucket", - "file": "compute_v1_generated_projects_set_usage_export_bucket_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_public_advertised_prefixes_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Projects_SetUsageExportBucket_sync", + "regionTag": "compute_v1_generated_PublicAdvertisedPrefixes_List_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -32336,12 +33628,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_projects_set_usage_export_bucket_sync.py" + "title": "compute_v1_generated_public_advertised_prefixes_list_sync.py" }, { "canonical": true, @@ -32350,19 +33642,19 @@ "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient", "shortName": "PublicAdvertisedPrefixesClient" }, - "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient.announce", + "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient.patch", "method": { - "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes.Announce", + "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes.Patch", "service": { "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes", "shortName": "PublicAdvertisedPrefixes" }, - "shortName": "Announce" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AnnouncePublicAdvertisedPrefixeRequest" + "type": "google.cloud.compute_v1.types.PatchPublicAdvertisedPrefixeRequest" }, { "name": "project", @@ -32372,6 +33664,10 @@ "name": "public_advertised_prefix", "type": "str" }, + { + "name": "public_advertised_prefix_resource", + "type": "google.cloud.compute_v1.types.PublicAdvertisedPrefix" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -32386,13 +33682,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "announce" + "shortName": "patch" }, - "description": "Sample for Announce", - "file": "compute_v1_generated_public_advertised_prefixes_announce_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_public_advertised_prefixes_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PublicAdvertisedPrefixes_Announce_sync", + "regionTag": "compute_v1_generated_PublicAdvertisedPrefixes_Patch_sync", "segments": [ { "end": 52, @@ -32425,7 +33721,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_public_advertised_prefixes_announce_sync.py" + "title": "compute_v1_generated_public_advertised_prefixes_patch_sync.py" }, { "canonical": true, @@ -32434,19 +33730,19 @@ "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient", "shortName": "PublicAdvertisedPrefixesClient" }, - "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient.delete", + "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient.withdraw", "method": { - "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes.Delete", + "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes.Withdraw", "service": { "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes", "shortName": "PublicAdvertisedPrefixes" }, - "shortName": "Delete" + "shortName": "Withdraw" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeletePublicAdvertisedPrefixeRequest" + "type": "google.cloud.compute_v1.types.WithdrawPublicAdvertisedPrefixeRequest" }, { "name": "project", @@ -32470,13 +33766,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "shortName": "withdraw" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_public_advertised_prefixes_delete_sync.py", + "description": "Sample for Withdraw", + "file": "compute_v1_generated_public_advertised_prefixes_withdraw_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PublicAdvertisedPrefixes_Delete_sync", + "regionTag": "compute_v1_generated_PublicAdvertisedPrefixes_Withdraw_sync", "segments": [ { "end": 52, @@ -32509,37 +33805,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_public_advertised_prefixes_delete_sync.py" + "title": "compute_v1_generated_public_advertised_prefixes_withdraw_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient", - "shortName": "PublicAdvertisedPrefixesClient" + "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient", + "shortName": "PublicDelegatedPrefixesClient" }, - "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient.get", + "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes.Get", + "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes.AggregatedList", "service": { - "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes", - "shortName": "PublicAdvertisedPrefixes" + "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes", + "shortName": "PublicDelegatedPrefixes" }, - "shortName": "Get" + "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetPublicAdvertisedPrefixeRequest" + "type": "google.cloud.compute_v1.types.AggregatedListPublicDelegatedPrefixesRequest" }, { "name": "project", "type": "str" }, - { - "name": "public_advertised_prefix", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -32553,14 +33845,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.PublicAdvertisedPrefix", - "shortName": "get" + "resultType": "google.cloud.compute_v1.services.public_delegated_prefixes.pagers.AggregatedListPager", + "shortName": "aggregated_list" }, - "description": "Sample for Get", - "file": "compute_v1_generated_public_advertised_prefixes_get_sync.py", + "description": "Sample for AggregatedList", + "file": "compute_v1_generated_public_delegated_prefixes_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PublicAdvertisedPrefixes_Get_sync", + "regionTag": "compute_v1_generated_PublicDelegatedPrefixes_AggregatedList_sync", "segments": [ { "end": 52, @@ -32578,51 +33870,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 50, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_public_advertised_prefixes_get_sync.py" + "title": "compute_v1_generated_public_delegated_prefixes_aggregated_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient", - "shortName": "PublicAdvertisedPrefixesClient" + "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient", + "shortName": "PublicDelegatedPrefixesClient" }, - "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient.insert", + "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient.announce", "method": { - "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes.Insert", + "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes.Announce", "service": { - "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes", - "shortName": "PublicAdvertisedPrefixes" + "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes", + "shortName": "PublicDelegatedPrefixes" }, - "shortName": "Insert" + "shortName": "Announce" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertPublicAdvertisedPrefixeRequest" + "type": "google.cloud.compute_v1.types.AnnouncePublicDelegatedPrefixeRequest" }, { "name": "project", "type": "str" }, { - "name": "public_advertised_prefix_resource", - "type": "google.cloud.compute_v1.types.PublicAdvertisedPrefix" + "name": "region", + "type": "str" + }, + { + "name": "public_delegated_prefix", + "type": "str" }, { "name": "retry", @@ -32638,21 +33934,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "shortName": "announce" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_public_advertised_prefixes_insert_sync.py", + "description": "Sample for Announce", + "file": "compute_v1_generated_public_delegated_prefixes_announce_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PublicAdvertisedPrefixes_Insert_sync", + "regionTag": "compute_v1_generated_PublicDelegatedPrefixes_Announce_sync", "segments": [ { - "end": 51, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 53, "start": 27, "type": "SHORT" }, @@ -32662,48 +33958,56 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_public_advertised_prefixes_insert_sync.py" + "title": "compute_v1_generated_public_delegated_prefixes_announce_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient", - "shortName": "PublicAdvertisedPrefixesClient" + "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient", + "shortName": "PublicDelegatedPrefixesClient" }, - "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient.list", + "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient.delete", "method": { - "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes.List", + "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes.Delete", "service": { - "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes", - "shortName": "PublicAdvertisedPrefixes" + "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes", + "shortName": "PublicDelegatedPrefixes" }, - "shortName": "List" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListPublicAdvertisedPrefixesRequest" + "type": "google.cloud.compute_v1.types.DeletePublicDelegatedPrefixeRequest" }, { "name": "project", "type": "str" }, + { + "name": "region", + "type": "str" + }, + { + "name": "public_delegated_prefix", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -32717,22 +34021,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.public_advertised_prefixes.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for List", - "file": "compute_v1_generated_public_advertised_prefixes_list_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_public_delegated_prefixes_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PublicAdvertisedPrefixes_List_sync", + "regionTag": "compute_v1_generated_PublicDelegatedPrefixes_Delete_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -32742,55 +34046,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_public_advertised_prefixes_list_sync.py" + "title": "compute_v1_generated_public_delegated_prefixes_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient", - "shortName": "PublicAdvertisedPrefixesClient" + "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient", + "shortName": "PublicDelegatedPrefixesClient" }, - "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient.patch", + "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient.get", "method": { - "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes.Patch", + "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes.Get", "service": { - "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes", - "shortName": "PublicAdvertisedPrefixes" + "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes", + "shortName": "PublicDelegatedPrefixes" }, - "shortName": "Patch" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchPublicAdvertisedPrefixeRequest" + "type": "google.cloud.compute_v1.types.GetPublicDelegatedPrefixeRequest" }, { "name": "project", "type": "str" }, { - "name": "public_advertised_prefix", + "name": "region", "type": "str" }, { - "name": "public_advertised_prefix_resource", - "type": "google.cloud.compute_v1.types.PublicAdvertisedPrefix" + "name": "public_delegated_prefix", + "type": "str" }, { "name": "retry", @@ -32805,22 +34109,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "resultType": "google.cloud.compute_v1.types.PublicDelegatedPrefix", + "shortName": "get" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_public_advertised_prefixes_patch_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_public_delegated_prefixes_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PublicAdvertisedPrefixes_Patch_sync", + "regionTag": "compute_v1_generated_PublicDelegatedPrefixes_Get_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -32830,52 +34134,56 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_public_advertised_prefixes_patch_sync.py" + "title": "compute_v1_generated_public_delegated_prefixes_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient", - "shortName": "PublicAdvertisedPrefixesClient" + "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient", + "shortName": "PublicDelegatedPrefixesClient" }, - "fullName": "google.cloud.compute_v1.PublicAdvertisedPrefixesClient.withdraw", + "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient.insert", "method": { - "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes.Withdraw", + "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes.Insert", "service": { - "fullName": "google.cloud.compute.v1.PublicAdvertisedPrefixes", - "shortName": "PublicAdvertisedPrefixes" + "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes", + "shortName": "PublicDelegatedPrefixes" }, - "shortName": "Withdraw" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.WithdrawPublicAdvertisedPrefixeRequest" + "type": "google.cloud.compute_v1.types.InsertPublicDelegatedPrefixeRequest" }, { "name": "project", "type": "str" }, { - "name": "public_advertised_prefix", + "name": "region", "type": "str" }, + { + "name": "public_delegated_prefix_resource", + "type": "google.cloud.compute_v1.types.PublicDelegatedPrefix" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -32890,13 +34198,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "withdraw" + "shortName": "insert" }, - "description": "Sample for Withdraw", - "file": "compute_v1_generated_public_advertised_prefixes_withdraw_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_public_delegated_prefixes_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PublicAdvertisedPrefixes_Withdraw_sync", + "regionTag": "compute_v1_generated_PublicDelegatedPrefixes_Insert_sync", "segments": [ { "end": 52, @@ -32929,7 +34237,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_public_advertised_prefixes_withdraw_sync.py" + "title": "compute_v1_generated_public_delegated_prefixes_insert_sync.py" }, { "canonical": true, @@ -32938,24 +34246,28 @@ "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient", "shortName": "PublicDelegatedPrefixesClient" }, - "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient.aggregated_list", + "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient.list", "method": { - "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes.AggregatedList", + "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes.List", "service": { "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes", "shortName": "PublicDelegatedPrefixes" }, - "shortName": "AggregatedList" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AggregatedListPublicDelegatedPrefixesRequest" + "type": "google.cloud.compute_v1.types.ListPublicDelegatedPrefixesRequest" }, { "name": "project", "type": "str" }, + { + "name": "region", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -32969,22 +34281,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.public_delegated_prefixes.pagers.AggregatedListPager", - "shortName": "aggregated_list" + "resultType": "google.cloud.compute_v1.services.public_delegated_prefixes.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for AggregatedList", - "file": "compute_v1_generated_public_delegated_prefixes_aggregated_list_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_public_delegated_prefixes_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PublicDelegatedPrefixes_AggregatedList_sync", + "regionTag": "compute_v1_generated_PublicDelegatedPrefixes_List_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -32994,22 +34306,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 54, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_public_delegated_prefixes_aggregated_list_sync.py" + "title": "compute_v1_generated_public_delegated_prefixes_list_sync.py" }, { "canonical": true, @@ -33018,19 +34330,19 @@ "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient", "shortName": "PublicDelegatedPrefixesClient" }, - "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient.announce", + "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient.patch", "method": { - "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes.Announce", + "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes.Patch", "service": { "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes", "shortName": "PublicDelegatedPrefixes" }, - "shortName": "Announce" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AnnouncePublicDelegatedPrefixeRequest" + "type": "google.cloud.compute_v1.types.PatchPublicDelegatedPrefixeRequest" }, { "name": "project", @@ -33044,6 +34356,10 @@ "name": "public_delegated_prefix", "type": "str" }, + { + "name": "public_delegated_prefix_resource", + "type": "google.cloud.compute_v1.types.PublicDelegatedPrefix" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -33058,13 +34374,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "announce" + "shortName": "patch" }, - "description": "Sample for Announce", - "file": "compute_v1_generated_public_delegated_prefixes_announce_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_public_delegated_prefixes_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PublicDelegatedPrefixes_Announce_sync", + "regionTag": "compute_v1_generated_PublicDelegatedPrefixes_Patch_sync", "segments": [ { "end": 53, @@ -33097,7 +34413,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_public_delegated_prefixes_announce_sync.py" + "title": "compute_v1_generated_public_delegated_prefixes_patch_sync.py" }, { "canonical": true, @@ -33106,19 +34422,19 @@ "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient", "shortName": "PublicDelegatedPrefixesClient" }, - "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient.delete", + "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient.withdraw", "method": { - "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes.Delete", + "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes.Withdraw", "service": { "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes", "shortName": "PublicDelegatedPrefixes" }, - "shortName": "Delete" + "shortName": "Withdraw" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeletePublicDelegatedPrefixeRequest" + "type": "google.cloud.compute_v1.types.WithdrawPublicDelegatedPrefixeRequest" }, { "name": "project", @@ -33146,13 +34462,101 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "withdraw" + }, + "description": "Sample for Withdraw", + "file": "compute_v1_generated_public_delegated_prefixes_withdraw_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_PublicDelegatedPrefixes_Withdraw_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_public_delegated_prefixes_withdraw_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.RegionAutoscalersClient", + "shortName": "RegionAutoscalersClient" + }, + "fullName": "google.cloud.compute_v1.RegionAutoscalersClient.delete", + "method": { + "fullName": "google.cloud.compute.v1.RegionAutoscalers.Delete", + "service": { + "fullName": "google.cloud.compute.v1.RegionAutoscalers", + "shortName": "RegionAutoscalers" + }, + "shortName": "Delete" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.DeleteRegionAutoscalerRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "autoscaler", + "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.extended_operation.ExtendedOperation", "shortName": "delete" }, "description": "Sample for Delete", - "file": "compute_v1_generated_public_delegated_prefixes_delete_sync.py", + "file": "compute_v1_generated_region_autoscalers_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PublicDelegatedPrefixes_Delete_sync", + "regionTag": "compute_v1_generated_RegionAutoscalers_Delete_sync", "segments": [ { "end": 53, @@ -33185,28 +34589,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_public_delegated_prefixes_delete_sync.py" + "title": "compute_v1_generated_region_autoscalers_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient", - "shortName": "PublicDelegatedPrefixesClient" + "fullName": "google.cloud.compute_v1.RegionAutoscalersClient", + "shortName": "RegionAutoscalersClient" }, - "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient.get", + "fullName": "google.cloud.compute_v1.RegionAutoscalersClient.get", "method": { - "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes.Get", + "fullName": "google.cloud.compute.v1.RegionAutoscalers.Get", "service": { - "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes", - "shortName": "PublicDelegatedPrefixes" + "fullName": "google.cloud.compute.v1.RegionAutoscalers", + "shortName": "RegionAutoscalers" }, "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetPublicDelegatedPrefixeRequest" + "type": "google.cloud.compute_v1.types.GetRegionAutoscalerRequest" }, { "name": "project", @@ -33217,7 +34621,7 @@ "type": "str" }, { - "name": "public_delegated_prefix", + "name": "autoscaler", "type": "str" }, { @@ -33233,14 +34637,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.PublicDelegatedPrefix", + "resultType": "google.cloud.compute_v1.types.Autoscaler", "shortName": "get" }, "description": "Sample for Get", - "file": "compute_v1_generated_public_delegated_prefixes_get_sync.py", + "file": "compute_v1_generated_region_autoscalers_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PublicDelegatedPrefixes_Get_sync", + "regionTag": "compute_v1_generated_RegionAutoscalers_Get_sync", "segments": [ { "end": 53, @@ -33273,28 +34677,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_public_delegated_prefixes_get_sync.py" + "title": "compute_v1_generated_region_autoscalers_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient", - "shortName": "PublicDelegatedPrefixesClient" + "fullName": "google.cloud.compute_v1.RegionAutoscalersClient", + "shortName": "RegionAutoscalersClient" }, - "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient.insert", + "fullName": "google.cloud.compute_v1.RegionAutoscalersClient.insert", "method": { - "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes.Insert", + "fullName": "google.cloud.compute.v1.RegionAutoscalers.Insert", "service": { - "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes", - "shortName": "PublicDelegatedPrefixes" + "fullName": "google.cloud.compute.v1.RegionAutoscalers", + "shortName": "RegionAutoscalers" }, "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertPublicDelegatedPrefixeRequest" + "type": "google.cloud.compute_v1.types.InsertRegionAutoscalerRequest" }, { "name": "project", @@ -33305,8 +34709,8 @@ "type": "str" }, { - "name": "public_delegated_prefix_resource", - "type": "google.cloud.compute_v1.types.PublicDelegatedPrefix" + "name": "autoscaler_resource", + "type": "google.cloud.compute_v1.types.Autoscaler" }, { "name": "retry", @@ -33325,10 +34729,10 @@ "shortName": "insert" }, "description": "Sample for Insert", - "file": "compute_v1_generated_public_delegated_prefixes_insert_sync.py", + "file": "compute_v1_generated_region_autoscalers_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PublicDelegatedPrefixes_Insert_sync", + "regionTag": "compute_v1_generated_RegionAutoscalers_Insert_sync", "segments": [ { "end": 52, @@ -33361,28 +34765,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_public_delegated_prefixes_insert_sync.py" + "title": "compute_v1_generated_region_autoscalers_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient", - "shortName": "PublicDelegatedPrefixesClient" + "fullName": "google.cloud.compute_v1.RegionAutoscalersClient", + "shortName": "RegionAutoscalersClient" }, - "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient.list", + "fullName": "google.cloud.compute_v1.RegionAutoscalersClient.list", "method": { - "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes.List", + "fullName": "google.cloud.compute.v1.RegionAutoscalers.List", "service": { - "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes", - "shortName": "PublicDelegatedPrefixes" + "fullName": "google.cloud.compute.v1.RegionAutoscalers", + "shortName": "RegionAutoscalers" }, "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListPublicDelegatedPrefixesRequest" + "type": "google.cloud.compute_v1.types.ListRegionAutoscalersRequest" }, { "name": "project", @@ -33405,14 +34809,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.public_delegated_prefixes.pagers.ListPager", + "resultType": "google.cloud.compute_v1.services.region_autoscalers.pagers.ListPager", "shortName": "list" }, "description": "Sample for List", - "file": "compute_v1_generated_public_delegated_prefixes_list_sync.py", + "file": "compute_v1_generated_region_autoscalers_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PublicDelegatedPrefixes_List_sync", + "regionTag": "compute_v1_generated_RegionAutoscalers_List_sync", "segments": [ { "end": 53, @@ -33445,28 +34849,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_public_delegated_prefixes_list_sync.py" + "title": "compute_v1_generated_region_autoscalers_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient", - "shortName": "PublicDelegatedPrefixesClient" + "fullName": "google.cloud.compute_v1.RegionAutoscalersClient", + "shortName": "RegionAutoscalersClient" }, - "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient.patch", + "fullName": "google.cloud.compute_v1.RegionAutoscalersClient.patch", "method": { - "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes.Patch", + "fullName": "google.cloud.compute.v1.RegionAutoscalers.Patch", "service": { - "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes", - "shortName": "PublicDelegatedPrefixes" + "fullName": "google.cloud.compute.v1.RegionAutoscalers", + "shortName": "RegionAutoscalers" }, "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchPublicDelegatedPrefixeRequest" + "type": "google.cloud.compute_v1.types.PatchRegionAutoscalerRequest" }, { "name": "project", @@ -33477,12 +34881,8 @@ "type": "str" }, { - "name": "public_delegated_prefix", - "type": "str" - }, - { - "name": "public_delegated_prefix_resource", - "type": "google.cloud.compute_v1.types.PublicDelegatedPrefix" + "name": "autoscaler_resource", + "type": "google.cloud.compute_v1.types.Autoscaler" }, { "name": "retry", @@ -33501,18 +34901,18 @@ "shortName": "patch" }, "description": "Sample for Patch", - "file": "compute_v1_generated_public_delegated_prefixes_patch_sync.py", + "file": "compute_v1_generated_region_autoscalers_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PublicDelegatedPrefixes_Patch_sync", + "regionTag": "compute_v1_generated_RegionAutoscalers_Patch_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -33522,43 +34922,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_public_delegated_prefixes_patch_sync.py" + "title": "compute_v1_generated_region_autoscalers_patch_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient", - "shortName": "PublicDelegatedPrefixesClient" + "fullName": "google.cloud.compute_v1.RegionAutoscalersClient", + "shortName": "RegionAutoscalersClient" }, - "fullName": "google.cloud.compute_v1.PublicDelegatedPrefixesClient.withdraw", + "fullName": "google.cloud.compute_v1.RegionAutoscalersClient.update", "method": { - "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes.Withdraw", + "fullName": "google.cloud.compute.v1.RegionAutoscalers.Update", "service": { - "fullName": "google.cloud.compute.v1.PublicDelegatedPrefixes", - "shortName": "PublicDelegatedPrefixes" + "fullName": "google.cloud.compute.v1.RegionAutoscalers", + "shortName": "RegionAutoscalers" }, - "shortName": "Withdraw" + "shortName": "Update" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.WithdrawPublicDelegatedPrefixeRequest" + "type": "google.cloud.compute_v1.types.UpdateRegionAutoscalerRequest" }, { "name": "project", @@ -33569,8 +34969,8 @@ "type": "str" }, { - "name": "public_delegated_prefix", - "type": "str" + "name": "autoscaler_resource", + "type": "google.cloud.compute_v1.types.Autoscaler" }, { "name": "retry", @@ -33586,21 +34986,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "withdraw" + "shortName": "update" }, - "description": "Sample for Withdraw", - "file": "compute_v1_generated_public_delegated_prefixes_withdraw_sync.py", + "description": "Sample for Update", + "file": "compute_v1_generated_region_autoscalers_update_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_PublicDelegatedPrefixes_Withdraw_sync", + "regionTag": "compute_v1_generated_RegionAutoscalers_Update_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -33610,43 +35010,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_public_delegated_prefixes_withdraw_sync.py" + "title": "compute_v1_generated_region_autoscalers_update_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionAutoscalersClient", - "shortName": "RegionAutoscalersClient" + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", + "shortName": "RegionBackendServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionAutoscalersClient.delete", + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.delete", "method": { - "fullName": "google.cloud.compute.v1.RegionAutoscalers.Delete", + "fullName": "google.cloud.compute.v1.RegionBackendServices.Delete", "service": { - "fullName": "google.cloud.compute.v1.RegionAutoscalers", - "shortName": "RegionAutoscalers" + "fullName": "google.cloud.compute.v1.RegionBackendServices", + "shortName": "RegionBackendServices" }, "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteRegionAutoscalerRequest" + "type": "google.cloud.compute_v1.types.DeleteRegionBackendServiceRequest" }, { "name": "project", @@ -33657,7 +35057,7 @@ "type": "str" }, { - "name": "autoscaler", + "name": "backend_service", "type": "str" }, { @@ -33677,10 +35077,10 @@ "shortName": "delete" }, "description": "Sample for Delete", - "file": "compute_v1_generated_region_autoscalers_delete_sync.py", + "file": "compute_v1_generated_region_backend_services_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionAutoscalers_Delete_sync", + "regionTag": "compute_v1_generated_RegionBackendServices_Delete_sync", "segments": [ { "end": 53, @@ -33713,28 +35113,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_autoscalers_delete_sync.py" + "title": "compute_v1_generated_region_backend_services_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionAutoscalersClient", - "shortName": "RegionAutoscalersClient" + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", + "shortName": "RegionBackendServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionAutoscalersClient.get", + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.get_health", "method": { - "fullName": "google.cloud.compute.v1.RegionAutoscalers.Get", + "fullName": "google.cloud.compute.v1.RegionBackendServices.GetHealth", "service": { - "fullName": "google.cloud.compute.v1.RegionAutoscalers", - "shortName": "RegionAutoscalers" + "fullName": "google.cloud.compute.v1.RegionBackendServices", + "shortName": "RegionBackendServices" }, - "shortName": "Get" + "shortName": "GetHealth" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetRegionAutoscalerRequest" + "type": "google.cloud.compute_v1.types.GetHealthRegionBackendServiceRequest" }, { "name": "project", @@ -33745,9 +35145,13 @@ "type": "str" }, { - "name": "autoscaler", + "name": "backend_service", "type": "str" }, + { + "name": "resource_group_reference_resource", + "type": "google.cloud.compute_v1.types.ResourceGroupReference" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -33761,14 +35165,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Autoscaler", - "shortName": "get" + "resultType": "google.cloud.compute_v1.types.BackendServiceGroupHealth", + "shortName": "get_health" }, - "description": "Sample for Get", - "file": "compute_v1_generated_region_autoscalers_get_sync.py", + "description": "Sample for GetHealth", + "file": "compute_v1_generated_region_backend_services_get_health_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionAutoscalers_Get_sync", + "regionTag": "compute_v1_generated_RegionBackendServices_GetHealth_sync", "segments": [ { "end": 53, @@ -33801,28 +35205,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_autoscalers_get_sync.py" + "title": "compute_v1_generated_region_backend_services_get_health_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionAutoscalersClient", - "shortName": "RegionAutoscalersClient" + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", + "shortName": "RegionBackendServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionAutoscalersClient.insert", + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.get_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.RegionAutoscalers.Insert", + "fullName": "google.cloud.compute.v1.RegionBackendServices.GetIamPolicy", "service": { - "fullName": "google.cloud.compute.v1.RegionAutoscalers", - "shortName": "RegionAutoscalers" + "fullName": "google.cloud.compute.v1.RegionBackendServices", + "shortName": "RegionBackendServices" }, - "shortName": "Insert" + "shortName": "GetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertRegionAutoscalerRequest" + "type": "google.cloud.compute_v1.types.GetIamPolicyRegionBackendServiceRequest" }, { "name": "project", @@ -33833,8 +35237,8 @@ "type": "str" }, { - "name": "autoscaler_resource", - "type": "google.cloud.compute_v1.types.Autoscaler" + "name": "resource", + "type": "str" }, { "name": "retry", @@ -33849,22 +35253,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "get_iam_policy" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_region_autoscalers_insert_sync.py", + "description": "Sample for GetIamPolicy", + "file": "compute_v1_generated_region_backend_services_get_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionAutoscalers_Insert_sync", + "regionTag": "compute_v1_generated_RegionBackendServices_GetIamPolicy_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -33874,43 +35278,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_autoscalers_insert_sync.py" + "title": "compute_v1_generated_region_backend_services_get_iam_policy_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionAutoscalersClient", - "shortName": "RegionAutoscalersClient" + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", + "shortName": "RegionBackendServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionAutoscalersClient.list", + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.get", "method": { - "fullName": "google.cloud.compute.v1.RegionAutoscalers.List", + "fullName": "google.cloud.compute.v1.RegionBackendServices.Get", "service": { - "fullName": "google.cloud.compute.v1.RegionAutoscalers", - "shortName": "RegionAutoscalers" + "fullName": "google.cloud.compute.v1.RegionBackendServices", + "shortName": "RegionBackendServices" }, - "shortName": "List" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListRegionAutoscalersRequest" + "type": "google.cloud.compute_v1.types.GetRegionBackendServiceRequest" }, { "name": "project", @@ -33920,6 +35324,10 @@ "name": "region", "type": "str" }, + { + "name": "backend_service", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -33933,14 +35341,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.region_autoscalers.pagers.ListPager", - "shortName": "list" + "resultType": "google.cloud.compute_v1.types.BackendService", + "shortName": "get" }, - "description": "Sample for List", - "file": "compute_v1_generated_region_autoscalers_list_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_region_backend_services_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionAutoscalers_List_sync", + "regionTag": "compute_v1_generated_RegionBackendServices_Get_sync", "segments": [ { "end": 53, @@ -33958,43 +35366,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 50, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_autoscalers_list_sync.py" + "title": "compute_v1_generated_region_backend_services_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionAutoscalersClient", - "shortName": "RegionAutoscalersClient" + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", + "shortName": "RegionBackendServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionAutoscalersClient.patch", + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.insert", "method": { - "fullName": "google.cloud.compute.v1.RegionAutoscalers.Patch", + "fullName": "google.cloud.compute.v1.RegionBackendServices.Insert", "service": { - "fullName": "google.cloud.compute.v1.RegionAutoscalers", - "shortName": "RegionAutoscalers" + "fullName": "google.cloud.compute.v1.RegionBackendServices", + "shortName": "RegionBackendServices" }, - "shortName": "Patch" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchRegionAutoscalerRequest" + "type": "google.cloud.compute_v1.types.InsertRegionBackendServiceRequest" }, { "name": "project", @@ -34005,8 +35413,8 @@ "type": "str" }, { - "name": "autoscaler_resource", - "type": "google.cloud.compute_v1.types.Autoscaler" + "name": "backend_service_resource", + "type": "google.cloud.compute_v1.types.BackendService" }, { "name": "retry", @@ -34022,13 +35430,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "shortName": "insert" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_region_autoscalers_patch_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_region_backend_services_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionAutoscalers_Patch_sync", + "regionTag": "compute_v1_generated_RegionBackendServices_Insert_sync", "segments": [ { "end": 52, @@ -34061,28 +35469,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_autoscalers_patch_sync.py" + "title": "compute_v1_generated_region_backend_services_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionAutoscalersClient", - "shortName": "RegionAutoscalersClient" + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", + "shortName": "RegionBackendServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionAutoscalersClient.update", + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.list_usable", "method": { - "fullName": "google.cloud.compute.v1.RegionAutoscalers.Update", + "fullName": "google.cloud.compute.v1.RegionBackendServices.ListUsable", "service": { - "fullName": "google.cloud.compute.v1.RegionAutoscalers", - "shortName": "RegionAutoscalers" + "fullName": "google.cloud.compute.v1.RegionBackendServices", + "shortName": "RegionBackendServices" }, - "shortName": "Update" + "shortName": "ListUsable" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.UpdateRegionAutoscalerRequest" + "type": "google.cloud.compute_v1.types.ListUsableRegionBackendServicesRequest" }, { "name": "project", @@ -34092,10 +35500,6 @@ "name": "region", "type": "str" }, - { - "name": "autoscaler_resource", - "type": "google.cloud.compute_v1.types.Autoscaler" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -34109,22 +35513,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "update" + "resultType": "google.cloud.compute_v1.services.region_backend_services.pagers.ListUsablePager", + "shortName": "list_usable" }, - "description": "Sample for Update", - "file": "compute_v1_generated_region_autoscalers_update_sync.py", + "description": "Sample for ListUsable", + "file": "compute_v1_generated_region_backend_services_list_usable_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionAutoscalers_Update_sync", + "regionTag": "compute_v1_generated_RegionBackendServices_ListUsable_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -34144,12 +35548,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 54, "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_autoscalers_update_sync.py" + "title": "compute_v1_generated_region_backend_services_list_usable_sync.py" }, { "canonical": true, @@ -34158,19 +35562,19 @@ "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", "shortName": "RegionBackendServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.delete", + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.list", "method": { - "fullName": "google.cloud.compute.v1.RegionBackendServices.Delete", + "fullName": "google.cloud.compute.v1.RegionBackendServices.List", "service": { "fullName": "google.cloud.compute.v1.RegionBackendServices", "shortName": "RegionBackendServices" }, - "shortName": "Delete" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteRegionBackendServiceRequest" + "type": "google.cloud.compute_v1.types.ListRegionBackendServicesRequest" }, { "name": "project", @@ -34180,10 +35584,6 @@ "name": "region", "type": "str" }, - { - "name": "backend_service", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -34197,14 +35597,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "resultType": "google.cloud.compute_v1.services.region_backend_services.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_region_backend_services_delete_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_region_backend_services_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionBackendServices_Delete_sync", + "regionTag": "compute_v1_generated_RegionBackendServices_List_sync", "segments": [ { "end": 53, @@ -34222,22 +35622,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 51, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_backend_services_delete_sync.py" + "title": "compute_v1_generated_region_backend_services_list_sync.py" }, { "canonical": true, @@ -34246,19 +35646,19 @@ "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", "shortName": "RegionBackendServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.get_health", + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.patch", "method": { - "fullName": "google.cloud.compute.v1.RegionBackendServices.GetHealth", + "fullName": "google.cloud.compute.v1.RegionBackendServices.Patch", "service": { "fullName": "google.cloud.compute.v1.RegionBackendServices", "shortName": "RegionBackendServices" }, - "shortName": "GetHealth" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetHealthRegionBackendServiceRequest" + "type": "google.cloud.compute_v1.types.PatchRegionBackendServiceRequest" }, { "name": "project", @@ -34273,8 +35673,8 @@ "type": "str" }, { - "name": "resource_group_reference_resource", - "type": "google.cloud.compute_v1.types.ResourceGroupReference" + "name": "backend_service_resource", + "type": "google.cloud.compute_v1.types.BackendService" }, { "name": "retry", @@ -34289,14 +35689,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.BackendServiceGroupHealth", - "shortName": "get_health" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "patch" }, - "description": "Sample for GetHealth", - "file": "compute_v1_generated_region_backend_services_get_health_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_region_backend_services_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionBackendServices_GetHealth_sync", + "regionTag": "compute_v1_generated_RegionBackendServices_Patch_sync", "segments": [ { "end": 53, @@ -34329,7 +35729,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_backend_services_get_health_sync.py" + "title": "compute_v1_generated_region_backend_services_patch_sync.py" }, { "canonical": true, @@ -34338,19 +35738,19 @@ "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", "shortName": "RegionBackendServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.get_iam_policy", + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.set_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.RegionBackendServices.GetIamPolicy", + "fullName": "google.cloud.compute.v1.RegionBackendServices.SetIamPolicy", "service": { "fullName": "google.cloud.compute.v1.RegionBackendServices", "shortName": "RegionBackendServices" }, - "shortName": "GetIamPolicy" + "shortName": "SetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetIamPolicyRegionBackendServiceRequest" + "type": "google.cloud.compute_v1.types.SetIamPolicyRegionBackendServiceRequest" }, { "name": "project", @@ -34364,6 +35764,10 @@ "name": "resource", "type": "str" }, + { + "name": "region_set_policy_request_resource", + "type": "google.cloud.compute_v1.types.RegionSetPolicyRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -34378,13 +35782,13 @@ } ], "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "get_iam_policy" + "shortName": "set_iam_policy" }, - "description": "Sample for GetIamPolicy", - "file": "compute_v1_generated_region_backend_services_get_iam_policy_sync.py", + "description": "Sample for SetIamPolicy", + "file": "compute_v1_generated_region_backend_services_set_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionBackendServices_GetIamPolicy_sync", + "regionTag": "compute_v1_generated_RegionBackendServices_SetIamPolicy_sync", "segments": [ { "end": 53, @@ -34417,7 +35821,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_backend_services_get_iam_policy_sync.py" + "title": "compute_v1_generated_region_backend_services_set_iam_policy_sync.py" }, { "canonical": true, @@ -34426,19 +35830,19 @@ "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", "shortName": "RegionBackendServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.get", + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.set_security_policy", "method": { - "fullName": "google.cloud.compute.v1.RegionBackendServices.Get", + "fullName": "google.cloud.compute.v1.RegionBackendServices.SetSecurityPolicy", "service": { "fullName": "google.cloud.compute.v1.RegionBackendServices", "shortName": "RegionBackendServices" }, - "shortName": "Get" + "shortName": "SetSecurityPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetRegionBackendServiceRequest" + "type": "google.cloud.compute_v1.types.SetSecurityPolicyRegionBackendServiceRequest" }, { "name": "project", @@ -34452,6 +35856,10 @@ "name": "backend_service", "type": "str" }, + { + "name": "security_policy_reference_resource", + "type": "google.cloud.compute_v1.types.SecurityPolicyReference" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -34465,14 +35873,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.BackendService", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "set_security_policy" }, - "description": "Sample for Get", - "file": "compute_v1_generated_region_backend_services_get_sync.py", + "description": "Sample for SetSecurityPolicy", + "file": "compute_v1_generated_region_backend_services_set_security_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionBackendServices_Get_sync", + "regionTag": "compute_v1_generated_RegionBackendServices_SetSecurityPolicy_sync", "segments": [ { "end": 53, @@ -34505,7 +35913,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_backend_services_get_sync.py" + "title": "compute_v1_generated_region_backend_services_set_security_policy_sync.py" }, { "canonical": true, @@ -34514,19 +35922,19 @@ "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", "shortName": "RegionBackendServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.insert", + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.test_iam_permissions", "method": { - "fullName": "google.cloud.compute.v1.RegionBackendServices.Insert", + "fullName": "google.cloud.compute.v1.RegionBackendServices.TestIamPermissions", "service": { "fullName": "google.cloud.compute.v1.RegionBackendServices", "shortName": "RegionBackendServices" }, - "shortName": "Insert" + "shortName": "TestIamPermissions" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertRegionBackendServiceRequest" + "type": "google.cloud.compute_v1.types.TestIamPermissionsRegionBackendServiceRequest" }, { "name": "project", @@ -34537,8 +35945,12 @@ "type": "str" }, { - "name": "backend_service_resource", - "type": "google.cloud.compute_v1.types.BackendService" + "name": "resource", + "type": "str" + }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1.types.TestPermissionsRequest" }, { "name": "retry", @@ -34553,22 +35965,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_region_backend_services_insert_sync.py", + "description": "Sample for TestIamPermissions", + "file": "compute_v1_generated_region_backend_services_test_iam_permissions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionBackendServices_Insert_sync", + "regionTag": "compute_v1_generated_RegionBackendServices_TestIamPermissions_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -34578,22 +35990,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_backend_services_insert_sync.py" + "title": "compute_v1_generated_region_backend_services_test_iam_permissions_sync.py" }, { "canonical": true, @@ -34602,19 +36014,19 @@ "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", "shortName": "RegionBackendServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.list_usable", + "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.update", "method": { - "fullName": "google.cloud.compute.v1.RegionBackendServices.ListUsable", + "fullName": "google.cloud.compute.v1.RegionBackendServices.Update", "service": { "fullName": "google.cloud.compute.v1.RegionBackendServices", "shortName": "RegionBackendServices" }, - "shortName": "ListUsable" + "shortName": "Update" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListUsableRegionBackendServicesRequest" + "type": "google.cloud.compute_v1.types.UpdateRegionBackendServiceRequest" }, { "name": "project", @@ -34624,6 +36036,14 @@ "name": "region", "type": "str" }, + { + "name": "backend_service", + "type": "str" + }, + { + "name": "backend_service_resource", + "type": "google.cloud.compute_v1.types.BackendService" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -34637,14 +36057,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.region_backend_services.pagers.ListUsablePager", - "shortName": "list_usable" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "update" }, - "description": "Sample for ListUsable", - "file": "compute_v1_generated_region_backend_services_list_usable_sync.py", + "description": "Sample for Update", + "file": "compute_v1_generated_region_backend_services_update_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionBackendServices_ListUsable_sync", + "regionTag": "compute_v1_generated_RegionBackendServices_Update_sync", "segments": [ { "end": 53, @@ -34662,52 +36082,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 50, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_backend_services_list_usable_sync.py" + "title": "compute_v1_generated_region_backend_services_update_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", - "shortName": "RegionBackendServicesClient" + "fullName": "google.cloud.compute_v1.RegionCommitmentsClient", + "shortName": "RegionCommitmentsClient" }, - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.list", + "fullName": "google.cloud.compute_v1.RegionCommitmentsClient.aggregated_list", "method": { - "fullName": "google.cloud.compute.v1.RegionBackendServices.List", + "fullName": "google.cloud.compute.v1.RegionCommitments.AggregatedList", "service": { - "fullName": "google.cloud.compute.v1.RegionBackendServices", - "shortName": "RegionBackendServices" + "fullName": "google.cloud.compute.v1.RegionCommitments", + "shortName": "RegionCommitments" }, - "shortName": "List" + "shortName": "AggregatedList" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListRegionBackendServicesRequest" + "type": "google.cloud.compute_v1.types.AggregatedListRegionCommitmentsRequest" }, { "name": "project", "type": "str" }, - { - "name": "region", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -34721,22 +36137,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.region_backend_services.pagers.ListPager", - "shortName": "list" + "resultType": "google.cloud.compute_v1.services.region_commitments.pagers.AggregatedListPager", + "shortName": "aggregated_list" }, - "description": "Sample for List", - "file": "compute_v1_generated_region_backend_services_list_sync.py", + "description": "Sample for AggregatedList", + "file": "compute_v1_generated_region_commitments_aggregated_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionBackendServices_List_sync", + "regionTag": "compute_v1_generated_RegionCommitments_AggregatedList_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -34746,43 +36162,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 50, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_backend_services_list_sync.py" + "title": "compute_v1_generated_region_commitments_aggregated_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", - "shortName": "RegionBackendServicesClient" + "fullName": "google.cloud.compute_v1.RegionCommitmentsClient", + "shortName": "RegionCommitmentsClient" }, - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.patch", + "fullName": "google.cloud.compute_v1.RegionCommitmentsClient.get", "method": { - "fullName": "google.cloud.compute.v1.RegionBackendServices.Patch", + "fullName": "google.cloud.compute.v1.RegionCommitments.Get", "service": { - "fullName": "google.cloud.compute.v1.RegionBackendServices", - "shortName": "RegionBackendServices" + "fullName": "google.cloud.compute.v1.RegionCommitments", + "shortName": "RegionCommitments" }, - "shortName": "Patch" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchRegionBackendServiceRequest" + "type": "google.cloud.compute_v1.types.GetRegionCommitmentRequest" }, { "name": "project", @@ -34793,13 +36209,9 @@ "type": "str" }, { - "name": "backend_service", + "name": "commitment", "type": "str" }, - { - "name": "backend_service_resource", - "type": "google.cloud.compute_v1.types.BackendService" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -34813,14 +36225,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "resultType": "google.cloud.compute_v1.types.Commitment", + "shortName": "get" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_region_backend_services_patch_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_region_commitments_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionBackendServices_Patch_sync", + "regionTag": "compute_v1_generated_RegionCommitments_Get_sync", "segments": [ { "end": 53, @@ -34853,28 +36265,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_backend_services_patch_sync.py" + "title": "compute_v1_generated_region_commitments_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", - "shortName": "RegionBackendServicesClient" + "fullName": "google.cloud.compute_v1.RegionCommitmentsClient", + "shortName": "RegionCommitmentsClient" }, - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.set_iam_policy", + "fullName": "google.cloud.compute_v1.RegionCommitmentsClient.insert", "method": { - "fullName": "google.cloud.compute.v1.RegionBackendServices.SetIamPolicy", + "fullName": "google.cloud.compute.v1.RegionCommitments.Insert", "service": { - "fullName": "google.cloud.compute.v1.RegionBackendServices", - "shortName": "RegionBackendServices" + "fullName": "google.cloud.compute.v1.RegionCommitments", + "shortName": "RegionCommitments" }, - "shortName": "SetIamPolicy" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetIamPolicyRegionBackendServiceRequest" + "type": "google.cloud.compute_v1.types.InsertRegionCommitmentRequest" }, { "name": "project", @@ -34885,12 +36297,8 @@ "type": "str" }, { - "name": "resource", - "type": "str" - }, - { - "name": "region_set_policy_request_resource", - "type": "google.cloud.compute_v1.types.RegionSetPolicyRequest" + "name": "commitment_resource", + "type": "google.cloud.compute_v1.types.Commitment" }, { "name": "retry", @@ -34905,22 +36313,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "set_iam_policy" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" }, - "description": "Sample for SetIamPolicy", - "file": "compute_v1_generated_region_backend_services_set_iam_policy_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_region_commitments_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionBackendServices_SetIamPolicy_sync", + "regionTag": "compute_v1_generated_RegionCommitments_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -34930,43 +36338,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_backend_services_set_iam_policy_sync.py" + "title": "compute_v1_generated_region_commitments_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", - "shortName": "RegionBackendServicesClient" + "fullName": "google.cloud.compute_v1.RegionCommitmentsClient", + "shortName": "RegionCommitmentsClient" }, - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.set_security_policy", + "fullName": "google.cloud.compute_v1.RegionCommitmentsClient.list", "method": { - "fullName": "google.cloud.compute.v1.RegionBackendServices.SetSecurityPolicy", + "fullName": "google.cloud.compute.v1.RegionCommitments.List", "service": { - "fullName": "google.cloud.compute.v1.RegionBackendServices", - "shortName": "RegionBackendServices" + "fullName": "google.cloud.compute.v1.RegionCommitments", + "shortName": "RegionCommitments" }, - "shortName": "SetSecurityPolicy" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetSecurityPolicyRegionBackendServiceRequest" + "type": "google.cloud.compute_v1.types.ListRegionCommitmentsRequest" }, { "name": "project", @@ -34976,14 +36384,6 @@ "name": "region", "type": "str" }, - { - "name": "backend_service", - "type": "str" - }, - { - "name": "security_policy_reference_resource", - "type": "google.cloud.compute_v1.types.SecurityPolicyReference" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -34997,14 +36397,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_security_policy" + "resultType": "google.cloud.compute_v1.services.region_commitments.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for SetSecurityPolicy", - "file": "compute_v1_generated_region_backend_services_set_security_policy_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_region_commitments_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionBackendServices_SetSecurityPolicy_sync", + "regionTag": "compute_v1_generated_RegionCommitments_List_sync", "segments": [ { "end": 53, @@ -35022,43 +36422,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 51, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_backend_services_set_security_policy_sync.py" + "title": "compute_v1_generated_region_commitments_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", - "shortName": "RegionBackendServicesClient" + "fullName": "google.cloud.compute_v1.RegionCommitmentsClient", + "shortName": "RegionCommitmentsClient" }, - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1.RegionCommitmentsClient.update", "method": { - "fullName": "google.cloud.compute.v1.RegionBackendServices.TestIamPermissions", + "fullName": "google.cloud.compute.v1.RegionCommitments.Update", "service": { - "fullName": "google.cloud.compute.v1.RegionBackendServices", - "shortName": "RegionBackendServices" + "fullName": "google.cloud.compute.v1.RegionCommitments", + "shortName": "RegionCommitments" }, - "shortName": "TestIamPermissions" + "shortName": "Update" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.TestIamPermissionsRegionBackendServiceRequest" + "type": "google.cloud.compute_v1.types.UpdateRegionCommitmentRequest" }, { "name": "project", @@ -35069,12 +36469,12 @@ "type": "str" }, { - "name": "resource", + "name": "commitment", "type": "str" }, { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1.types.TestPermissionsRequest" + "name": "commitment_resource", + "type": "google.cloud.compute_v1.types.Commitment" }, { "name": "retry", @@ -35089,14 +36489,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "update" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1_generated_region_backend_services_test_iam_permissions_sync.py", + "description": "Sample for Update", + "file": "compute_v1_generated_region_commitments_update_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionBackendServices_TestIamPermissions_sync", + "regionTag": "compute_v1_generated_RegionCommitments_Update_sync", "segments": [ { "end": 53, @@ -35129,28 +36529,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_backend_services_test_iam_permissions_sync.py" + "title": "compute_v1_generated_region_commitments_update_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient", - "shortName": "RegionBackendServicesClient" + "fullName": "google.cloud.compute_v1.RegionDiskTypesClient", + "shortName": "RegionDiskTypesClient" }, - "fullName": "google.cloud.compute_v1.RegionBackendServicesClient.update", + "fullName": "google.cloud.compute_v1.RegionDiskTypesClient.get", "method": { - "fullName": "google.cloud.compute.v1.RegionBackendServices.Update", + "fullName": "google.cloud.compute.v1.RegionDiskTypes.Get", "service": { - "fullName": "google.cloud.compute.v1.RegionBackendServices", - "shortName": "RegionBackendServices" + "fullName": "google.cloud.compute.v1.RegionDiskTypes", + "shortName": "RegionDiskTypes" }, - "shortName": "Update" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.UpdateRegionBackendServiceRequest" + "type": "google.cloud.compute_v1.types.GetRegionDiskTypeRequest" }, { "name": "project", @@ -35161,13 +36561,9 @@ "type": "str" }, { - "name": "backend_service", + "name": "disk_type", "type": "str" }, - { - "name": "backend_service_resource", - "type": "google.cloud.compute_v1.types.BackendService" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -35181,14 +36577,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "update" + "resultType": "google.cloud.compute_v1.types.DiskType", + "shortName": "get" }, - "description": "Sample for Update", - "file": "compute_v1_generated_region_backend_services_update_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_region_disk_types_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionBackendServices_Update_sync", + "regionTag": "compute_v1_generated_RegionDiskTypes_Get_sync", "segments": [ { "end": 53, @@ -35221,33 +36617,37 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_backend_services_update_sync.py" + "title": "compute_v1_generated_region_disk_types_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionCommitmentsClient", - "shortName": "RegionCommitmentsClient" + "fullName": "google.cloud.compute_v1.RegionDiskTypesClient", + "shortName": "RegionDiskTypesClient" }, - "fullName": "google.cloud.compute_v1.RegionCommitmentsClient.aggregated_list", + "fullName": "google.cloud.compute_v1.RegionDiskTypesClient.list", "method": { - "fullName": "google.cloud.compute.v1.RegionCommitments.AggregatedList", + "fullName": "google.cloud.compute.v1.RegionDiskTypes.List", "service": { - "fullName": "google.cloud.compute.v1.RegionCommitments", - "shortName": "RegionCommitments" + "fullName": "google.cloud.compute.v1.RegionDiskTypes", + "shortName": "RegionDiskTypes" }, - "shortName": "AggregatedList" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AggregatedListRegionCommitmentsRequest" + "type": "google.cloud.compute_v1.types.ListRegionDiskTypesRequest" }, { "name": "project", "type": "str" }, + { + "name": "region", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -35261,22 +36661,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.region_commitments.pagers.AggregatedListPager", - "shortName": "aggregated_list" + "resultType": "google.cloud.compute_v1.services.region_disk_types.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for AggregatedList", - "file": "compute_v1_generated_region_commitments_aggregated_list_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_region_disk_types_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionCommitments_AggregatedList_sync", + "regionTag": "compute_v1_generated_RegionDiskTypes_List_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -35286,43 +36686,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 54, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_commitments_aggregated_list_sync.py" + "title": "compute_v1_generated_region_disk_types_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionCommitmentsClient", - "shortName": "RegionCommitmentsClient" + "fullName": "google.cloud.compute_v1.RegionDisksClient", + "shortName": "RegionDisksClient" }, - "fullName": "google.cloud.compute_v1.RegionCommitmentsClient.get", + "fullName": "google.cloud.compute_v1.RegionDisksClient.add_resource_policies", "method": { - "fullName": "google.cloud.compute.v1.RegionCommitments.Get", + "fullName": "google.cloud.compute.v1.RegionDisks.AddResourcePolicies", "service": { - "fullName": "google.cloud.compute.v1.RegionCommitments", - "shortName": "RegionCommitments" + "fullName": "google.cloud.compute.v1.RegionDisks", + "shortName": "RegionDisks" }, - "shortName": "Get" + "shortName": "AddResourcePolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetRegionCommitmentRequest" + "type": "google.cloud.compute_v1.types.AddResourcePoliciesRegionDiskRequest" }, { "name": "project", @@ -35333,9 +36733,13 @@ "type": "str" }, { - "name": "commitment", + "name": "disk", "type": "str" }, + { + "name": "region_disks_add_resource_policies_request_resource", + "type": "google.cloud.compute_v1.types.RegionDisksAddResourcePoliciesRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -35349,14 +36753,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Commitment", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "add_resource_policies" }, - "description": "Sample for Get", - "file": "compute_v1_generated_region_commitments_get_sync.py", + "description": "Sample for AddResourcePolicies", + "file": "compute_v1_generated_region_disks_add_resource_policies_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionCommitments_Get_sync", + "regionTag": "compute_v1_generated_RegionDisks_AddResourcePolicies_sync", "segments": [ { "end": 53, @@ -35389,28 +36793,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_commitments_get_sync.py" + "title": "compute_v1_generated_region_disks_add_resource_policies_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionCommitmentsClient", - "shortName": "RegionCommitmentsClient" + "fullName": "google.cloud.compute_v1.RegionDisksClient", + "shortName": "RegionDisksClient" }, - "fullName": "google.cloud.compute_v1.RegionCommitmentsClient.insert", + "fullName": "google.cloud.compute_v1.RegionDisksClient.bulk_insert", "method": { - "fullName": "google.cloud.compute.v1.RegionCommitments.Insert", + "fullName": "google.cloud.compute.v1.RegionDisks.BulkInsert", "service": { - "fullName": "google.cloud.compute.v1.RegionCommitments", - "shortName": "RegionCommitments" + "fullName": "google.cloud.compute.v1.RegionDisks", + "shortName": "RegionDisks" }, - "shortName": "Insert" + "shortName": "BulkInsert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertRegionCommitmentRequest" + "type": "google.cloud.compute_v1.types.BulkInsertRegionDiskRequest" }, { "name": "project", @@ -35421,8 +36825,8 @@ "type": "str" }, { - "name": "commitment_resource", - "type": "google.cloud.compute_v1.types.Commitment" + "name": "bulk_insert_disk_resource_resource", + "type": "google.cloud.compute_v1.types.BulkInsertDiskResource" }, { "name": "retry", @@ -35438,13 +36842,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "shortName": "bulk_insert" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_region_commitments_insert_sync.py", + "description": "Sample for BulkInsert", + "file": "compute_v1_generated_region_disks_bulk_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionCommitments_Insert_sync", + "regionTag": "compute_v1_generated_RegionDisks_BulkInsert_sync", "segments": [ { "end": 52, @@ -35477,28 +36881,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_commitments_insert_sync.py" + "title": "compute_v1_generated_region_disks_bulk_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionCommitmentsClient", - "shortName": "RegionCommitmentsClient" + "fullName": "google.cloud.compute_v1.RegionDisksClient", + "shortName": "RegionDisksClient" }, - "fullName": "google.cloud.compute_v1.RegionCommitmentsClient.list", + "fullName": "google.cloud.compute_v1.RegionDisksClient.create_snapshot", "method": { - "fullName": "google.cloud.compute.v1.RegionCommitments.List", + "fullName": "google.cloud.compute.v1.RegionDisks.CreateSnapshot", "service": { - "fullName": "google.cloud.compute.v1.RegionCommitments", - "shortName": "RegionCommitments" + "fullName": "google.cloud.compute.v1.RegionDisks", + "shortName": "RegionDisks" }, - "shortName": "List" + "shortName": "CreateSnapshot" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListRegionCommitmentsRequest" + "type": "google.cloud.compute_v1.types.CreateSnapshotRegionDiskRequest" }, { "name": "project", @@ -35508,6 +36912,14 @@ "name": "region", "type": "str" }, + { + "name": "disk", + "type": "str" + }, + { + "name": "snapshot_resource", + "type": "google.cloud.compute_v1.types.Snapshot" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -35521,14 +36933,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.region_commitments.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "create_snapshot" }, - "description": "Sample for List", - "file": "compute_v1_generated_region_commitments_list_sync.py", + "description": "Sample for CreateSnapshot", + "file": "compute_v1_generated_region_disks_create_snapshot_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionCommitments_List_sync", + "regionTag": "compute_v1_generated_RegionDisks_CreateSnapshot_sync", "segments": [ { "end": 53, @@ -35546,43 +36958,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 50, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_commitments_list_sync.py" + "title": "compute_v1_generated_region_disks_create_snapshot_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionCommitmentsClient", - "shortName": "RegionCommitmentsClient" + "fullName": "google.cloud.compute_v1.RegionDisksClient", + "shortName": "RegionDisksClient" }, - "fullName": "google.cloud.compute_v1.RegionCommitmentsClient.update", + "fullName": "google.cloud.compute_v1.RegionDisksClient.delete", "method": { - "fullName": "google.cloud.compute.v1.RegionCommitments.Update", + "fullName": "google.cloud.compute.v1.RegionDisks.Delete", "service": { - "fullName": "google.cloud.compute.v1.RegionCommitments", - "shortName": "RegionCommitments" + "fullName": "google.cloud.compute.v1.RegionDisks", + "shortName": "RegionDisks" }, - "shortName": "Update" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.UpdateRegionCommitmentRequest" + "type": "google.cloud.compute_v1.types.DeleteRegionDiskRequest" }, { "name": "project", @@ -35593,13 +37005,9 @@ "type": "str" }, { - "name": "commitment", + "name": "disk", "type": "str" }, - { - "name": "commitment_resource", - "type": "google.cloud.compute_v1.types.Commitment" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -35614,13 +37022,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "update" + "shortName": "delete" }, - "description": "Sample for Update", - "file": "compute_v1_generated_region_commitments_update_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_region_disks_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionCommitments_Update_sync", + "regionTag": "compute_v1_generated_RegionDisks_Delete_sync", "segments": [ { "end": 53, @@ -35653,28 +37061,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_commitments_update_sync.py" + "title": "compute_v1_generated_region_disks_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionDiskTypesClient", - "shortName": "RegionDiskTypesClient" + "fullName": "google.cloud.compute_v1.RegionDisksClient", + "shortName": "RegionDisksClient" }, - "fullName": "google.cloud.compute_v1.RegionDiskTypesClient.get", + "fullName": "google.cloud.compute_v1.RegionDisksClient.get_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.RegionDiskTypes.Get", + "fullName": "google.cloud.compute.v1.RegionDisks.GetIamPolicy", "service": { - "fullName": "google.cloud.compute.v1.RegionDiskTypes", - "shortName": "RegionDiskTypes" + "fullName": "google.cloud.compute.v1.RegionDisks", + "shortName": "RegionDisks" }, - "shortName": "Get" + "shortName": "GetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetRegionDiskTypeRequest" + "type": "google.cloud.compute_v1.types.GetIamPolicyRegionDiskRequest" }, { "name": "project", @@ -35685,7 +37093,7 @@ "type": "str" }, { - "name": "disk_type", + "name": "resource", "type": "str" }, { @@ -35701,14 +37109,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.DiskType", - "shortName": "get" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "get_iam_policy" }, - "description": "Sample for Get", - "file": "compute_v1_generated_region_disk_types_get_sync.py", + "description": "Sample for GetIamPolicy", + "file": "compute_v1_generated_region_disks_get_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDiskTypes_Get_sync", + "regionTag": "compute_v1_generated_RegionDisks_GetIamPolicy_sync", "segments": [ { "end": 53, @@ -35741,28 +37149,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disk_types_get_sync.py" + "title": "compute_v1_generated_region_disks_get_iam_policy_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionDiskTypesClient", - "shortName": "RegionDiskTypesClient" + "fullName": "google.cloud.compute_v1.RegionDisksClient", + "shortName": "RegionDisksClient" }, - "fullName": "google.cloud.compute_v1.RegionDiskTypesClient.list", + "fullName": "google.cloud.compute_v1.RegionDisksClient.get", "method": { - "fullName": "google.cloud.compute.v1.RegionDiskTypes.List", + "fullName": "google.cloud.compute.v1.RegionDisks.Get", "service": { - "fullName": "google.cloud.compute.v1.RegionDiskTypes", - "shortName": "RegionDiskTypes" + "fullName": "google.cloud.compute.v1.RegionDisks", + "shortName": "RegionDisks" }, - "shortName": "List" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListRegionDiskTypesRequest" + "type": "google.cloud.compute_v1.types.GetRegionDiskRequest" }, { "name": "project", @@ -35772,6 +37180,10 @@ "name": "region", "type": "str" }, + { + "name": "disk", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -35785,14 +37197,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.region_disk_types.pagers.ListPager", - "shortName": "list" + "resultType": "google.cloud.compute_v1.types.Disk", + "shortName": "get" }, - "description": "Sample for List", - "file": "compute_v1_generated_region_disk_types_list_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_region_disks_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDiskTypes_List_sync", + "regionTag": "compute_v1_generated_RegionDisks_Get_sync", "segments": [ { "end": 53, @@ -35810,22 +37222,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 50, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disk_types_list_sync.py" + "title": "compute_v1_generated_region_disks_get_sync.py" }, { "canonical": true, @@ -35834,19 +37246,19 @@ "fullName": "google.cloud.compute_v1.RegionDisksClient", "shortName": "RegionDisksClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.add_resource_policies", + "fullName": "google.cloud.compute_v1.RegionDisksClient.insert", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.AddResourcePolicies", + "fullName": "google.cloud.compute.v1.RegionDisks.Insert", "service": { "fullName": "google.cloud.compute.v1.RegionDisks", "shortName": "RegionDisks" }, - "shortName": "AddResourcePolicies" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AddResourcePoliciesRegionDiskRequest" + "type": "google.cloud.compute_v1.types.InsertRegionDiskRequest" }, { "name": "project", @@ -35857,12 +37269,8 @@ "type": "str" }, { - "name": "disk", - "type": "str" - }, - { - "name": "region_disks_add_resource_policies_request_resource", - "type": "google.cloud.compute_v1.types.RegionDisksAddResourcePoliciesRequest" + "name": "disk_resource", + "type": "google.cloud.compute_v1.types.Disk" }, { "name": "retry", @@ -35878,21 +37286,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "add_resource_policies" + "shortName": "insert" }, - "description": "Sample for AddResourcePolicies", - "file": "compute_v1_generated_region_disks_add_resource_policies_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_region_disks_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_AddResourcePolicies_sync", + "regionTag": "compute_v1_generated_RegionDisks_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -35902,22 +37310,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_add_resource_policies_sync.py" + "title": "compute_v1_generated_region_disks_insert_sync.py" }, { "canonical": true, @@ -35926,19 +37334,19 @@ "fullName": "google.cloud.compute_v1.RegionDisksClient", "shortName": "RegionDisksClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.bulk_insert", + "fullName": "google.cloud.compute_v1.RegionDisksClient.list", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.BulkInsert", + "fullName": "google.cloud.compute.v1.RegionDisks.List", "service": { "fullName": "google.cloud.compute.v1.RegionDisks", "shortName": "RegionDisks" }, - "shortName": "BulkInsert" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.BulkInsertRegionDiskRequest" + "type": "google.cloud.compute_v1.types.ListRegionDisksRequest" }, { "name": "project", @@ -35948,10 +37356,6 @@ "name": "region", "type": "str" }, - { - "name": "bulk_insert_disk_resource_resource", - "type": "google.cloud.compute_v1.types.BulkInsertDiskResource" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -35965,22 +37369,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "bulk_insert" + "resultType": "google.cloud.compute_v1.services.region_disks.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for BulkInsert", - "file": "compute_v1_generated_region_disks_bulk_insert_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_region_disks_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_BulkInsert_sync", + "regionTag": "compute_v1_generated_RegionDisks_List_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -36000,12 +37404,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 54, "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_bulk_insert_sync.py" + "title": "compute_v1_generated_region_disks_list_sync.py" }, { "canonical": true, @@ -36014,19 +37418,19 @@ "fullName": "google.cloud.compute_v1.RegionDisksClient", "shortName": "RegionDisksClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.create_snapshot", + "fullName": "google.cloud.compute_v1.RegionDisksClient.remove_resource_policies", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.CreateSnapshot", + "fullName": "google.cloud.compute.v1.RegionDisks.RemoveResourcePolicies", "service": { "fullName": "google.cloud.compute.v1.RegionDisks", "shortName": "RegionDisks" }, - "shortName": "CreateSnapshot" + "shortName": "RemoveResourcePolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.CreateSnapshotRegionDiskRequest" + "type": "google.cloud.compute_v1.types.RemoveResourcePoliciesRegionDiskRequest" }, { "name": "project", @@ -36041,8 +37445,8 @@ "type": "str" }, { - "name": "snapshot_resource", - "type": "google.cloud.compute_v1.types.Snapshot" + "name": "region_disks_remove_resource_policies_request_resource", + "type": "google.cloud.compute_v1.types.RegionDisksRemoveResourcePoliciesRequest" }, { "name": "retry", @@ -36058,13 +37462,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "create_snapshot" + "shortName": "remove_resource_policies" }, - "description": "Sample for CreateSnapshot", - "file": "compute_v1_generated_region_disks_create_snapshot_sync.py", + "description": "Sample for RemoveResourcePolicies", + "file": "compute_v1_generated_region_disks_remove_resource_policies_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_CreateSnapshot_sync", + "regionTag": "compute_v1_generated_RegionDisks_RemoveResourcePolicies_sync", "segments": [ { "end": 53, @@ -36097,7 +37501,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_create_snapshot_sync.py" + "title": "compute_v1_generated_region_disks_remove_resource_policies_sync.py" }, { "canonical": true, @@ -36106,19 +37510,19 @@ "fullName": "google.cloud.compute_v1.RegionDisksClient", "shortName": "RegionDisksClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.delete", + "fullName": "google.cloud.compute_v1.RegionDisksClient.resize", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.Delete", + "fullName": "google.cloud.compute.v1.RegionDisks.Resize", "service": { "fullName": "google.cloud.compute.v1.RegionDisks", "shortName": "RegionDisks" }, - "shortName": "Delete" + "shortName": "Resize" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteRegionDiskRequest" + "type": "google.cloud.compute_v1.types.ResizeRegionDiskRequest" }, { "name": "project", @@ -36132,6 +37536,10 @@ "name": "disk", "type": "str" }, + { + "name": "region_disks_resize_request_resource", + "type": "google.cloud.compute_v1.types.RegionDisksResizeRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -36146,13 +37554,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "shortName": "resize" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_region_disks_delete_sync.py", + "description": "Sample for Resize", + "file": "compute_v1_generated_region_disks_resize_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_Delete_sync", + "regionTag": "compute_v1_generated_RegionDisks_Resize_sync", "segments": [ { "end": 53, @@ -36185,7 +37593,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_delete_sync.py" + "title": "compute_v1_generated_region_disks_resize_sync.py" }, { "canonical": true, @@ -36194,19 +37602,19 @@ "fullName": "google.cloud.compute_v1.RegionDisksClient", "shortName": "RegionDisksClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.get_iam_policy", + "fullName": "google.cloud.compute_v1.RegionDisksClient.set_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.GetIamPolicy", + "fullName": "google.cloud.compute.v1.RegionDisks.SetIamPolicy", "service": { "fullName": "google.cloud.compute.v1.RegionDisks", "shortName": "RegionDisks" }, - "shortName": "GetIamPolicy" + "shortName": "SetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetIamPolicyRegionDiskRequest" + "type": "google.cloud.compute_v1.types.SetIamPolicyRegionDiskRequest" }, { "name": "project", @@ -36220,6 +37628,10 @@ "name": "resource", "type": "str" }, + { + "name": "region_set_policy_request_resource", + "type": "google.cloud.compute_v1.types.RegionSetPolicyRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -36234,13 +37646,13 @@ } ], "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "get_iam_policy" + "shortName": "set_iam_policy" }, - "description": "Sample for GetIamPolicy", - "file": "compute_v1_generated_region_disks_get_iam_policy_sync.py", + "description": "Sample for SetIamPolicy", + "file": "compute_v1_generated_region_disks_set_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_GetIamPolicy_sync", + "regionTag": "compute_v1_generated_RegionDisks_SetIamPolicy_sync", "segments": [ { "end": 53, @@ -36273,7 +37685,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_get_iam_policy_sync.py" + "title": "compute_v1_generated_region_disks_set_iam_policy_sync.py" }, { "canonical": true, @@ -36282,19 +37694,19 @@ "fullName": "google.cloud.compute_v1.RegionDisksClient", "shortName": "RegionDisksClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.get", + "fullName": "google.cloud.compute_v1.RegionDisksClient.set_labels", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.Get", + "fullName": "google.cloud.compute.v1.RegionDisks.SetLabels", "service": { "fullName": "google.cloud.compute.v1.RegionDisks", "shortName": "RegionDisks" }, - "shortName": "Get" + "shortName": "SetLabels" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetRegionDiskRequest" + "type": "google.cloud.compute_v1.types.SetLabelsRegionDiskRequest" }, { "name": "project", @@ -36305,9 +37717,13 @@ "type": "str" }, { - "name": "disk", + "name": "resource", "type": "str" }, + { + "name": "region_set_labels_request_resource", + "type": "google.cloud.compute_v1.types.RegionSetLabelsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -36321,14 +37737,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Disk", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "set_labels" }, - "description": "Sample for Get", - "file": "compute_v1_generated_region_disks_get_sync.py", + "description": "Sample for SetLabels", + "file": "compute_v1_generated_region_disks_set_labels_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_Get_sync", + "regionTag": "compute_v1_generated_RegionDisks_SetLabels_sync", "segments": [ { "end": 53, @@ -36361,7 +37777,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_get_sync.py" + "title": "compute_v1_generated_region_disks_set_labels_sync.py" }, { "canonical": true, @@ -36370,19 +37786,19 @@ "fullName": "google.cloud.compute_v1.RegionDisksClient", "shortName": "RegionDisksClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.insert", + "fullName": "google.cloud.compute_v1.RegionDisksClient.start_async_replication", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.Insert", + "fullName": "google.cloud.compute.v1.RegionDisks.StartAsyncReplication", "service": { "fullName": "google.cloud.compute.v1.RegionDisks", "shortName": "RegionDisks" }, - "shortName": "Insert" + "shortName": "StartAsyncReplication" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertRegionDiskRequest" + "type": "google.cloud.compute_v1.types.StartAsyncReplicationRegionDiskRequest" }, { "name": "project", @@ -36393,8 +37809,12 @@ "type": "str" }, { - "name": "disk_resource", - "type": "google.cloud.compute_v1.types.Disk" + "name": "disk", + "type": "str" + }, + { + "name": "region_disks_start_async_replication_request_resource", + "type": "google.cloud.compute_v1.types.RegionDisksStartAsyncReplicationRequest" }, { "name": "retry", @@ -36410,21 +37830,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "shortName": "start_async_replication" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_region_disks_insert_sync.py", + "description": "Sample for StartAsyncReplication", + "file": "compute_v1_generated_region_disks_start_async_replication_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_Insert_sync", + "regionTag": "compute_v1_generated_RegionDisks_StartAsyncReplication_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -36434,22 +37854,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_insert_sync.py" + "title": "compute_v1_generated_region_disks_start_async_replication_sync.py" }, { "canonical": true, @@ -36458,19 +37878,19 @@ "fullName": "google.cloud.compute_v1.RegionDisksClient", "shortName": "RegionDisksClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.list", + "fullName": "google.cloud.compute_v1.RegionDisksClient.stop_async_replication", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.List", + "fullName": "google.cloud.compute.v1.RegionDisks.StopAsyncReplication", "service": { "fullName": "google.cloud.compute.v1.RegionDisks", "shortName": "RegionDisks" }, - "shortName": "List" + "shortName": "StopAsyncReplication" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListRegionDisksRequest" + "type": "google.cloud.compute_v1.types.StopAsyncReplicationRegionDiskRequest" }, { "name": "project", @@ -36480,6 +37900,10 @@ "name": "region", "type": "str" }, + { + "name": "disk", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -36493,14 +37917,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.region_disks.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "stop_async_replication" }, - "description": "Sample for List", - "file": "compute_v1_generated_region_disks_list_sync.py", + "description": "Sample for StopAsyncReplication", + "file": "compute_v1_generated_region_disks_stop_async_replication_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_List_sync", + "regionTag": "compute_v1_generated_RegionDisks_StopAsyncReplication_sync", "segments": [ { "end": 53, @@ -36517,6 +37941,94 @@ "start": 38, "type": "CLIENT_INITIALIZATION" }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_region_disks_stop_async_replication_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.RegionDisksClient", + "shortName": "RegionDisksClient" + }, + "fullName": "google.cloud.compute_v1.RegionDisksClient.stop_group_async_replication", + "method": { + "fullName": "google.cloud.compute.v1.RegionDisks.StopGroupAsyncReplication", + "service": { + "fullName": "google.cloud.compute.v1.RegionDisks", + "shortName": "RegionDisks" + }, + "shortName": "StopGroupAsyncReplication" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.StopGroupAsyncReplicationRegionDiskRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "disks_stop_group_async_replication_resource_resource", + "type": "google.cloud.compute_v1.types.DisksStopGroupAsyncReplicationResource" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "stop_group_async_replication" + }, + "description": "Sample for StopGroupAsyncReplication", + "file": "compute_v1_generated_region_disks_stop_group_async_replication_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_RegionDisks_StopGroupAsyncReplication_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, @@ -36528,12 +38040,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 54, + "end": 53, "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_list_sync.py" + "title": "compute_v1_generated_region_disks_stop_group_async_replication_sync.py" }, { "canonical": true, @@ -36542,19 +38054,19 @@ "fullName": "google.cloud.compute_v1.RegionDisksClient", "shortName": "RegionDisksClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.remove_resource_policies", + "fullName": "google.cloud.compute_v1.RegionDisksClient.test_iam_permissions", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.RemoveResourcePolicies", + "fullName": "google.cloud.compute.v1.RegionDisks.TestIamPermissions", "service": { "fullName": "google.cloud.compute.v1.RegionDisks", "shortName": "RegionDisks" }, - "shortName": "RemoveResourcePolicies" + "shortName": "TestIamPermissions" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.RemoveResourcePoliciesRegionDiskRequest" + "type": "google.cloud.compute_v1.types.TestIamPermissionsRegionDiskRequest" }, { "name": "project", @@ -36565,12 +38077,12 @@ "type": "str" }, { - "name": "disk", + "name": "resource", "type": "str" }, { - "name": "region_disks_remove_resource_policies_request_resource", - "type": "google.cloud.compute_v1.types.RegionDisksRemoveResourcePoliciesRequest" + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1.types.TestPermissionsRequest" }, { "name": "retry", @@ -36585,14 +38097,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "remove_resource_policies" + "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" }, - "description": "Sample for RemoveResourcePolicies", - "file": "compute_v1_generated_region_disks_remove_resource_policies_sync.py", + "description": "Sample for TestIamPermissions", + "file": "compute_v1_generated_region_disks_test_iam_permissions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_RemoveResourcePolicies_sync", + "regionTag": "compute_v1_generated_RegionDisks_TestIamPermissions_sync", "segments": [ { "end": 53, @@ -36625,7 +38137,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_remove_resource_policies_sync.py" + "title": "compute_v1_generated_region_disks_test_iam_permissions_sync.py" }, { "canonical": true, @@ -36634,19 +38146,19 @@ "fullName": "google.cloud.compute_v1.RegionDisksClient", "shortName": "RegionDisksClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.resize", + "fullName": "google.cloud.compute_v1.RegionDisksClient.update", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.Resize", + "fullName": "google.cloud.compute.v1.RegionDisks.Update", "service": { "fullName": "google.cloud.compute.v1.RegionDisks", "shortName": "RegionDisks" }, - "shortName": "Resize" + "shortName": "Update" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ResizeRegionDiskRequest" + "type": "google.cloud.compute_v1.types.UpdateRegionDiskRequest" }, { "name": "project", @@ -36661,8 +38173,8 @@ "type": "str" }, { - "name": "region_disks_resize_request_resource", - "type": "google.cloud.compute_v1.types.RegionDisksResizeRequest" + "name": "disk_resource", + "type": "google.cloud.compute_v1.types.Disk" }, { "name": "retry", @@ -36678,13 +38190,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "resize" + "shortName": "update" }, - "description": "Sample for Resize", - "file": "compute_v1_generated_region_disks_resize_sync.py", + "description": "Sample for Update", + "file": "compute_v1_generated_region_disks_update_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_Resize_sync", + "regionTag": "compute_v1_generated_RegionDisks_Update_sync", "segments": [ { "end": 53, @@ -36717,28 +38229,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_resize_sync.py" + "title": "compute_v1_generated_region_disks_update_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionDisksClient", - "shortName": "RegionDisksClient" + "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient", + "shortName": "RegionHealthCheckServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.set_iam_policy", + "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient.delete", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.SetIamPolicy", + "fullName": "google.cloud.compute.v1.RegionHealthCheckServices.Delete", "service": { - "fullName": "google.cloud.compute.v1.RegionDisks", - "shortName": "RegionDisks" + "fullName": "google.cloud.compute.v1.RegionHealthCheckServices", + "shortName": "RegionHealthCheckServices" }, - "shortName": "SetIamPolicy" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetIamPolicyRegionDiskRequest" + "type": "google.cloud.compute_v1.types.DeleteRegionHealthCheckServiceRequest" }, { "name": "project", @@ -36749,13 +38261,9 @@ "type": "str" }, { - "name": "resource", + "name": "health_check_service", "type": "str" }, - { - "name": "region_set_policy_request_resource", - "type": "google.cloud.compute_v1.types.RegionSetPolicyRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -36769,14 +38277,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.Policy", - "shortName": "set_iam_policy" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for SetIamPolicy", - "file": "compute_v1_generated_region_disks_set_iam_policy_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_region_health_check_services_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_SetIamPolicy_sync", + "regionTag": "compute_v1_generated_RegionHealthCheckServices_Delete_sync", "segments": [ { "end": 53, @@ -36809,28 +38317,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_set_iam_policy_sync.py" + "title": "compute_v1_generated_region_health_check_services_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionDisksClient", - "shortName": "RegionDisksClient" + "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient", + "shortName": "RegionHealthCheckServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.set_labels", + "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient.get", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.SetLabels", + "fullName": "google.cloud.compute.v1.RegionHealthCheckServices.Get", "service": { - "fullName": "google.cloud.compute.v1.RegionDisks", - "shortName": "RegionDisks" + "fullName": "google.cloud.compute.v1.RegionHealthCheckServices", + "shortName": "RegionHealthCheckServices" }, - "shortName": "SetLabels" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetLabelsRegionDiskRequest" + "type": "google.cloud.compute_v1.types.GetRegionHealthCheckServiceRequest" }, { "name": "project", @@ -36841,13 +38349,9 @@ "type": "str" }, { - "name": "resource", + "name": "health_check_service", "type": "str" }, - { - "name": "region_set_labels_request_resource", - "type": "google.cloud.compute_v1.types.RegionSetLabelsRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -36861,14 +38365,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_labels" + "resultType": "google.cloud.compute_v1.types.HealthCheckService", + "shortName": "get" }, - "description": "Sample for SetLabels", - "file": "compute_v1_generated_region_disks_set_labels_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_region_health_check_services_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_SetLabels_sync", + "regionTag": "compute_v1_generated_RegionHealthCheckServices_Get_sync", "segments": [ { "end": 53, @@ -36901,28 +38405,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_set_labels_sync.py" + "title": "compute_v1_generated_region_health_check_services_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionDisksClient", - "shortName": "RegionDisksClient" + "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient", + "shortName": "RegionHealthCheckServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.start_async_replication", + "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient.insert", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.StartAsyncReplication", + "fullName": "google.cloud.compute.v1.RegionHealthCheckServices.Insert", "service": { - "fullName": "google.cloud.compute.v1.RegionDisks", - "shortName": "RegionDisks" + "fullName": "google.cloud.compute.v1.RegionHealthCheckServices", + "shortName": "RegionHealthCheckServices" }, - "shortName": "StartAsyncReplication" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.StartAsyncReplicationRegionDiskRequest" + "type": "google.cloud.compute_v1.types.InsertRegionHealthCheckServiceRequest" }, { "name": "project", @@ -36933,12 +38437,8 @@ "type": "str" }, { - "name": "disk", - "type": "str" - }, - { - "name": "region_disks_start_async_replication_request_resource", - "type": "google.cloud.compute_v1.types.RegionDisksStartAsyncReplicationRequest" + "name": "health_check_service_resource", + "type": "google.cloud.compute_v1.types.HealthCheckService" }, { "name": "retry", @@ -36954,21 +38454,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "start_async_replication" + "shortName": "insert" }, - "description": "Sample for StartAsyncReplication", - "file": "compute_v1_generated_region_disks_start_async_replication_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_region_health_check_services_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_StartAsyncReplication_sync", + "regionTag": "compute_v1_generated_RegionHealthCheckServices_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -36978,43 +38478,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_start_async_replication_sync.py" + "title": "compute_v1_generated_region_health_check_services_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionDisksClient", - "shortName": "RegionDisksClient" + "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient", + "shortName": "RegionHealthCheckServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.stop_async_replication", + "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient.list", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.StopAsyncReplication", + "fullName": "google.cloud.compute.v1.RegionHealthCheckServices.List", "service": { - "fullName": "google.cloud.compute.v1.RegionDisks", - "shortName": "RegionDisks" + "fullName": "google.cloud.compute.v1.RegionHealthCheckServices", + "shortName": "RegionHealthCheckServices" }, - "shortName": "StopAsyncReplication" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.StopAsyncReplicationRegionDiskRequest" + "type": "google.cloud.compute_v1.types.ListRegionHealthCheckServicesRequest" }, { "name": "project", @@ -37024,10 +38524,6 @@ "name": "region", "type": "str" }, - { - "name": "disk", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -37041,14 +38537,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "stop_async_replication" + "resultType": "google.cloud.compute_v1.services.region_health_check_services.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for StopAsyncReplication", - "file": "compute_v1_generated_region_disks_stop_async_replication_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_region_health_check_services_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_StopAsyncReplication_sync", + "regionTag": "compute_v1_generated_RegionHealthCheckServices_List_sync", "segments": [ { "end": 53, @@ -37066,43 +38562,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 51, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_stop_async_replication_sync.py" + "title": "compute_v1_generated_region_health_check_services_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionDisksClient", - "shortName": "RegionDisksClient" + "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient", + "shortName": "RegionHealthCheckServicesClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.stop_group_async_replication", + "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient.patch", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.StopGroupAsyncReplication", + "fullName": "google.cloud.compute.v1.RegionHealthCheckServices.Patch", "service": { - "fullName": "google.cloud.compute.v1.RegionDisks", - "shortName": "RegionDisks" + "fullName": "google.cloud.compute.v1.RegionHealthCheckServices", + "shortName": "RegionHealthCheckServices" }, - "shortName": "StopGroupAsyncReplication" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.StopGroupAsyncReplicationRegionDiskRequest" + "type": "google.cloud.compute_v1.types.PatchRegionHealthCheckServiceRequest" }, { "name": "project", @@ -37113,8 +38609,12 @@ "type": "str" }, { - "name": "disks_stop_group_async_replication_resource_resource", - "type": "google.cloud.compute_v1.types.DisksStopGroupAsyncReplicationResource" + "name": "health_check_service", + "type": "str" + }, + { + "name": "health_check_service_resource", + "type": "google.cloud.compute_v1.types.HealthCheckService" }, { "name": "retry", @@ -37130,21 +38630,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "stop_group_async_replication" + "shortName": "patch" }, - "description": "Sample for StopGroupAsyncReplication", - "file": "compute_v1_generated_region_disks_stop_group_async_replication_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_region_health_check_services_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_StopGroupAsyncReplication_sync", + "regionTag": "compute_v1_generated_RegionHealthCheckServices_Patch_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -37154,43 +38654,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_stop_group_async_replication_sync.py" + "title": "compute_v1_generated_region_health_check_services_patch_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionDisksClient", - "shortName": "RegionDisksClient" + "fullName": "google.cloud.compute_v1.RegionHealthChecksClient", + "shortName": "RegionHealthChecksClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.test_iam_permissions", + "fullName": "google.cloud.compute_v1.RegionHealthChecksClient.delete", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.TestIamPermissions", + "fullName": "google.cloud.compute.v1.RegionHealthChecks.Delete", "service": { - "fullName": "google.cloud.compute.v1.RegionDisks", - "shortName": "RegionDisks" + "fullName": "google.cloud.compute.v1.RegionHealthChecks", + "shortName": "RegionHealthChecks" }, - "shortName": "TestIamPermissions" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.TestIamPermissionsRegionDiskRequest" + "type": "google.cloud.compute_v1.types.DeleteRegionHealthCheckRequest" }, { "name": "project", @@ -37201,13 +38701,9 @@ "type": "str" }, { - "name": "resource", + "name": "health_check", "type": "str" }, - { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1.types.TestPermissionsRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -37221,14 +38717,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", - "shortName": "test_iam_permissions" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1_generated_region_disks_test_iam_permissions_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_region_health_checks_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_TestIamPermissions_sync", + "regionTag": "compute_v1_generated_RegionHealthChecks_Delete_sync", "segments": [ { "end": 53, @@ -37261,28 +38757,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_test_iam_permissions_sync.py" + "title": "compute_v1_generated_region_health_checks_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionDisksClient", - "shortName": "RegionDisksClient" + "fullName": "google.cloud.compute_v1.RegionHealthChecksClient", + "shortName": "RegionHealthChecksClient" }, - "fullName": "google.cloud.compute_v1.RegionDisksClient.update", + "fullName": "google.cloud.compute_v1.RegionHealthChecksClient.get", "method": { - "fullName": "google.cloud.compute.v1.RegionDisks.Update", + "fullName": "google.cloud.compute.v1.RegionHealthChecks.Get", "service": { - "fullName": "google.cloud.compute.v1.RegionDisks", - "shortName": "RegionDisks" + "fullName": "google.cloud.compute.v1.RegionHealthChecks", + "shortName": "RegionHealthChecks" }, - "shortName": "Update" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.UpdateRegionDiskRequest" + "type": "google.cloud.compute_v1.types.GetRegionHealthCheckRequest" }, { "name": "project", @@ -37293,13 +38789,9 @@ "type": "str" }, { - "name": "disk", + "name": "health_check", "type": "str" }, - { - "name": "disk_resource", - "type": "google.cloud.compute_v1.types.Disk" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -37313,14 +38805,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "update" + "resultType": "google.cloud.compute_v1.types.HealthCheck", + "shortName": "get" }, - "description": "Sample for Update", - "file": "compute_v1_generated_region_disks_update_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_region_health_checks_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionDisks_Update_sync", + "regionTag": "compute_v1_generated_RegionHealthChecks_Get_sync", "segments": [ { "end": 53, @@ -37353,28 +38845,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_disks_update_sync.py" + "title": "compute_v1_generated_region_health_checks_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient", - "shortName": "RegionHealthCheckServicesClient" + "fullName": "google.cloud.compute_v1.RegionHealthChecksClient", + "shortName": "RegionHealthChecksClient" }, - "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient.delete", + "fullName": "google.cloud.compute_v1.RegionHealthChecksClient.insert", "method": { - "fullName": "google.cloud.compute.v1.RegionHealthCheckServices.Delete", + "fullName": "google.cloud.compute.v1.RegionHealthChecks.Insert", "service": { - "fullName": "google.cloud.compute.v1.RegionHealthCheckServices", - "shortName": "RegionHealthCheckServices" + "fullName": "google.cloud.compute.v1.RegionHealthChecks", + "shortName": "RegionHealthChecks" }, - "shortName": "Delete" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteRegionHealthCheckServiceRequest" + "type": "google.cloud.compute_v1.types.InsertRegionHealthCheckRequest" }, { "name": "project", @@ -37385,8 +38877,8 @@ "type": "str" }, { - "name": "health_check_service", - "type": "str" + "name": "health_check_resource", + "type": "google.cloud.compute_v1.types.HealthCheck" }, { "name": "retry", @@ -37402,21 +38894,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "shortName": "insert" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_region_health_check_services_delete_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_region_health_checks_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionHealthCheckServices_Delete_sync", + "regionTag": "compute_v1_generated_RegionHealthChecks_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -37426,43 +38918,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_health_check_services_delete_sync.py" + "title": "compute_v1_generated_region_health_checks_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient", - "shortName": "RegionHealthCheckServicesClient" + "fullName": "google.cloud.compute_v1.RegionHealthChecksClient", + "shortName": "RegionHealthChecksClient" }, - "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient.get", + "fullName": "google.cloud.compute_v1.RegionHealthChecksClient.list", "method": { - "fullName": "google.cloud.compute.v1.RegionHealthCheckServices.Get", + "fullName": "google.cloud.compute.v1.RegionHealthChecks.List", "service": { - "fullName": "google.cloud.compute.v1.RegionHealthCheckServices", - "shortName": "RegionHealthCheckServices" + "fullName": "google.cloud.compute.v1.RegionHealthChecks", + "shortName": "RegionHealthChecks" }, - "shortName": "Get" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetRegionHealthCheckServiceRequest" + "type": "google.cloud.compute_v1.types.ListRegionHealthChecksRequest" }, { "name": "project", @@ -37472,10 +38964,6 @@ "name": "region", "type": "str" }, - { - "name": "health_check_service", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -37489,14 +38977,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.HealthCheckService", - "shortName": "get" + "resultType": "google.cloud.compute_v1.services.region_health_checks.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Get", - "file": "compute_v1_generated_region_health_check_services_get_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_region_health_checks_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionHealthCheckServices_Get_sync", + "regionTag": "compute_v1_generated_RegionHealthChecks_List_sync", "segments": [ { "end": 53, @@ -37514,43 +39002,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 51, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_health_check_services_get_sync.py" + "title": "compute_v1_generated_region_health_checks_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient", - "shortName": "RegionHealthCheckServicesClient" + "fullName": "google.cloud.compute_v1.RegionHealthChecksClient", + "shortName": "RegionHealthChecksClient" }, - "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient.insert", + "fullName": "google.cloud.compute_v1.RegionHealthChecksClient.patch", "method": { - "fullName": "google.cloud.compute.v1.RegionHealthCheckServices.Insert", + "fullName": "google.cloud.compute.v1.RegionHealthChecks.Patch", "service": { - "fullName": "google.cloud.compute.v1.RegionHealthCheckServices", - "shortName": "RegionHealthCheckServices" + "fullName": "google.cloud.compute.v1.RegionHealthChecks", + "shortName": "RegionHealthChecks" }, - "shortName": "Insert" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertRegionHealthCheckServiceRequest" + "type": "google.cloud.compute_v1.types.PatchRegionHealthCheckRequest" }, { "name": "project", @@ -37561,8 +39049,12 @@ "type": "str" }, { - "name": "health_check_service_resource", - "type": "google.cloud.compute_v1.types.HealthCheckService" + "name": "health_check", + "type": "str" + }, + { + "name": "health_check_resource", + "type": "google.cloud.compute_v1.types.HealthCheck" }, { "name": "retry", @@ -37578,21 +39070,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "shortName": "patch" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_region_health_check_services_insert_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_region_health_checks_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionHealthCheckServices_Insert_sync", + "regionTag": "compute_v1_generated_RegionHealthChecks_Patch_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -37602,43 +39094,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_health_check_services_insert_sync.py" + "title": "compute_v1_generated_region_health_checks_patch_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient", - "shortName": "RegionHealthCheckServicesClient" + "fullName": "google.cloud.compute_v1.RegionHealthChecksClient", + "shortName": "RegionHealthChecksClient" }, - "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient.list", + "fullName": "google.cloud.compute_v1.RegionHealthChecksClient.update", "method": { - "fullName": "google.cloud.compute.v1.RegionHealthCheckServices.List", + "fullName": "google.cloud.compute.v1.RegionHealthChecks.Update", "service": { - "fullName": "google.cloud.compute.v1.RegionHealthCheckServices", - "shortName": "RegionHealthCheckServices" + "fullName": "google.cloud.compute.v1.RegionHealthChecks", + "shortName": "RegionHealthChecks" }, - "shortName": "List" + "shortName": "Update" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListRegionHealthCheckServicesRequest" + "type": "google.cloud.compute_v1.types.UpdateRegionHealthCheckRequest" }, { "name": "project", @@ -37648,6 +39140,14 @@ "name": "region", "type": "str" }, + { + "name": "health_check", + "type": "str" + }, + { + "name": "health_check_resource", + "type": "google.cloud.compute_v1.types.HealthCheck" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -37661,14 +39161,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.region_health_check_services.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "update" }, - "description": "Sample for List", - "file": "compute_v1_generated_region_health_check_services_list_sync.py", + "description": "Sample for Update", + "file": "compute_v1_generated_region_health_checks_update_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionHealthCheckServices_List_sync", + "regionTag": "compute_v1_generated_RegionHealthChecks_Update_sync", "segments": [ { "end": 53, @@ -37686,43 +39186,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 50, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_health_check_services_list_sync.py" + "title": "compute_v1_generated_region_health_checks_update_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient", - "shortName": "RegionHealthCheckServicesClient" + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", + "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionHealthCheckServicesClient.patch", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.abandon_instances", "method": { - "fullName": "google.cloud.compute.v1.RegionHealthCheckServices.Patch", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.AbandonInstances", "service": { - "fullName": "google.cloud.compute.v1.RegionHealthCheckServices", - "shortName": "RegionHealthCheckServices" + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", + "shortName": "RegionInstanceGroupManagers" }, - "shortName": "Patch" + "shortName": "AbandonInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchRegionHealthCheckServiceRequest" + "type": "google.cloud.compute_v1.types.AbandonInstancesRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -37733,12 +39233,12 @@ "type": "str" }, { - "name": "health_check_service", + "name": "instance_group_manager", "type": "str" }, { - "name": "health_check_service_resource", - "type": "google.cloud.compute_v1.types.HealthCheckService" + "name": "region_instance_group_managers_abandon_instances_request_resource", + "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagersAbandonInstancesRequest" }, { "name": "retry", @@ -37754,13 +39254,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "shortName": "abandon_instances" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_region_health_check_services_patch_sync.py", + "description": "Sample for AbandonInstances", + "file": "compute_v1_generated_region_instance_group_managers_abandon_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionHealthCheckServices_Patch_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_AbandonInstances_sync", "segments": [ { "end": 53, @@ -37793,28 +39293,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_health_check_services_patch_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_abandon_instances_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionHealthChecksClient", - "shortName": "RegionHealthChecksClient" + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", + "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionHealthChecksClient.delete", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.apply_updates_to_instances", "method": { - "fullName": "google.cloud.compute.v1.RegionHealthChecks.Delete", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.ApplyUpdatesToInstances", "service": { - "fullName": "google.cloud.compute.v1.RegionHealthChecks", - "shortName": "RegionHealthChecks" + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", + "shortName": "RegionInstanceGroupManagers" }, - "shortName": "Delete" + "shortName": "ApplyUpdatesToInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteRegionHealthCheckRequest" + "type": "google.cloud.compute_v1.types.ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -37825,9 +39325,13 @@ "type": "str" }, { - "name": "health_check", + "name": "instance_group_manager", "type": "str" }, + { + "name": "region_instance_group_managers_apply_updates_request_resource", + "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagersApplyUpdatesRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -37842,13 +39346,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "shortName": "apply_updates_to_instances" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_region_health_checks_delete_sync.py", + "description": "Sample for ApplyUpdatesToInstances", + "file": "compute_v1_generated_region_instance_group_managers_apply_updates_to_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionHealthChecks_Delete_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_ApplyUpdatesToInstances_sync", "segments": [ { "end": 53, @@ -37881,28 +39385,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_health_checks_delete_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_apply_updates_to_instances_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionHealthChecksClient", - "shortName": "RegionHealthChecksClient" + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", + "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionHealthChecksClient.get", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.create_instances", "method": { - "fullName": "google.cloud.compute.v1.RegionHealthChecks.Get", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.CreateInstances", "service": { - "fullName": "google.cloud.compute.v1.RegionHealthChecks", - "shortName": "RegionHealthChecks" + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", + "shortName": "RegionInstanceGroupManagers" }, - "shortName": "Get" + "shortName": "CreateInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetRegionHealthCheckRequest" + "type": "google.cloud.compute_v1.types.CreateInstancesRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -37913,9 +39417,13 @@ "type": "str" }, { - "name": "health_check", + "name": "instance_group_manager", "type": "str" }, + { + "name": "region_instance_group_managers_create_instances_request_resource", + "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagersCreateInstancesRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -37929,14 +39437,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.HealthCheck", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "create_instances" }, - "description": "Sample for Get", - "file": "compute_v1_generated_region_health_checks_get_sync.py", + "description": "Sample for CreateInstances", + "file": "compute_v1_generated_region_instance_group_managers_create_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionHealthChecks_Get_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_CreateInstances_sync", "segments": [ { "end": 53, @@ -37969,28 +39477,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_health_checks_get_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_create_instances_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionHealthChecksClient", - "shortName": "RegionHealthChecksClient" + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", + "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionHealthChecksClient.insert", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.delete_instances", "method": { - "fullName": "google.cloud.compute.v1.RegionHealthChecks.Insert", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.DeleteInstances", "service": { - "fullName": "google.cloud.compute.v1.RegionHealthChecks", - "shortName": "RegionHealthChecks" + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", + "shortName": "RegionInstanceGroupManagers" }, - "shortName": "Insert" + "shortName": "DeleteInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertRegionHealthCheckRequest" + "type": "google.cloud.compute_v1.types.DeleteInstancesRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -38001,8 +39509,12 @@ "type": "str" }, { - "name": "health_check_resource", - "type": "google.cloud.compute_v1.types.HealthCheck" + "name": "instance_group_manager", + "type": "str" + }, + { + "name": "region_instance_group_managers_delete_instances_request_resource", + "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagersDeleteInstancesRequest" }, { "name": "retry", @@ -38018,21 +39530,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "shortName": "delete_instances" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_region_health_checks_insert_sync.py", + "description": "Sample for DeleteInstances", + "file": "compute_v1_generated_region_instance_group_managers_delete_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionHealthChecks_Insert_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_DeleteInstances_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -38042,43 +39554,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_health_checks_insert_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_delete_instances_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionHealthChecksClient", - "shortName": "RegionHealthChecksClient" + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", + "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionHealthChecksClient.list", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.delete_per_instance_configs", "method": { - "fullName": "google.cloud.compute.v1.RegionHealthChecks.List", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.DeletePerInstanceConfigs", "service": { - "fullName": "google.cloud.compute.v1.RegionHealthChecks", - "shortName": "RegionHealthChecks" + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", + "shortName": "RegionInstanceGroupManagers" }, - "shortName": "List" + "shortName": "DeletePerInstanceConfigs" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListRegionHealthChecksRequest" + "type": "google.cloud.compute_v1.types.DeletePerInstanceConfigsRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -38088,6 +39600,14 @@ "name": "region", "type": "str" }, + { + "name": "instance_group_manager", + "type": "str" + }, + { + "name": "region_instance_group_manager_delete_instance_config_req_resource", + "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagerDeleteInstanceConfigReq" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -38101,14 +39621,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.region_health_checks.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete_per_instance_configs" }, - "description": "Sample for List", - "file": "compute_v1_generated_region_health_checks_list_sync.py", + "description": "Sample for DeletePerInstanceConfigs", + "file": "compute_v1_generated_region_instance_group_managers_delete_per_instance_configs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionHealthChecks_List_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_DeletePerInstanceConfigs_sync", "segments": [ { "end": 53, @@ -38126,43 +39646,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 50, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_health_checks_list_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_delete_per_instance_configs_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionHealthChecksClient", - "shortName": "RegionHealthChecksClient" + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", + "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionHealthChecksClient.patch", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.delete", "method": { - "fullName": "google.cloud.compute.v1.RegionHealthChecks.Patch", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.Delete", "service": { - "fullName": "google.cloud.compute.v1.RegionHealthChecks", - "shortName": "RegionHealthChecks" + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", + "shortName": "RegionInstanceGroupManagers" }, - "shortName": "Patch" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchRegionHealthCheckRequest" + "type": "google.cloud.compute_v1.types.DeleteRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -38173,13 +39693,9 @@ "type": "str" }, { - "name": "health_check", + "name": "instance_group_manager", "type": "str" }, - { - "name": "health_check_resource", - "type": "google.cloud.compute_v1.types.HealthCheck" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -38194,13 +39710,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "shortName": "delete" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_region_health_checks_patch_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_region_instance_group_managers_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionHealthChecks_Patch_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_Delete_sync", "segments": [ { "end": 53, @@ -38233,28 +39749,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_health_checks_patch_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionHealthChecksClient", - "shortName": "RegionHealthChecksClient" + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", + "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionHealthChecksClient.update", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.get", "method": { - "fullName": "google.cloud.compute.v1.RegionHealthChecks.Update", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.Get", "service": { - "fullName": "google.cloud.compute.v1.RegionHealthChecks", - "shortName": "RegionHealthChecks" + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", + "shortName": "RegionInstanceGroupManagers" }, - "shortName": "Update" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.UpdateRegionHealthCheckRequest" + "type": "google.cloud.compute_v1.types.GetRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -38265,13 +39781,9 @@ "type": "str" }, { - "name": "health_check", + "name": "instance_group_manager", "type": "str" }, - { - "name": "health_check_resource", - "type": "google.cloud.compute_v1.types.HealthCheck" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -38285,14 +39797,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "update" + "resultType": "google.cloud.compute_v1.types.InstanceGroupManager", + "shortName": "get" }, - "description": "Sample for Update", - "file": "compute_v1_generated_region_health_checks_update_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_region_instance_group_managers_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionHealthChecks_Update_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_Get_sync", "segments": [ { "end": 53, @@ -38325,7 +39837,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_health_checks_update_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_get_sync.py" }, { "canonical": true, @@ -38334,19 +39846,19 @@ "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.abandon_instances", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.insert", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.AbandonInstances", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.Insert", "service": { "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "AbandonInstances" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.AbandonInstancesRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1.types.InsertRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -38357,12 +39869,8 @@ "type": "str" }, { - "name": "instance_group_manager", - "type": "str" - }, - { - "name": "region_instance_group_managers_abandon_instances_request_resource", - "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagersAbandonInstancesRequest" + "name": "instance_group_manager_resource", + "type": "google.cloud.compute_v1.types.InstanceGroupManager" }, { "name": "retry", @@ -38378,21 +39886,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "abandon_instances" + "shortName": "insert" }, - "description": "Sample for AbandonInstances", - "file": "compute_v1_generated_region_instance_group_managers_abandon_instances_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_region_instance_group_managers_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_AbandonInstances_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -38402,22 +39910,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_abandon_instances_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_insert_sync.py" }, { "canonical": true, @@ -38426,19 +39934,19 @@ "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.apply_updates_to_instances", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.list_errors", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.ApplyUpdatesToInstances", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.ListErrors", "service": { "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "ApplyUpdatesToInstances" + "shortName": "ListErrors" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ApplyUpdatesToInstancesRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1.types.ListErrorsRegionInstanceGroupManagersRequest" }, { "name": "project", @@ -38452,10 +39960,6 @@ "name": "instance_group_manager", "type": "str" }, - { - "name": "region_instance_group_managers_apply_updates_request_resource", - "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagersApplyUpdatesRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -38469,22 +39973,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "apply_updates_to_instances" + "resultType": "google.cloud.compute_v1.services.region_instance_group_managers.pagers.ListErrorsPager", + "shortName": "list_errors" }, - "description": "Sample for ApplyUpdatesToInstances", - "file": "compute_v1_generated_region_instance_group_managers_apply_updates_to_instances_sync.py", + "description": "Sample for ListErrors", + "file": "compute_v1_generated_region_instance_group_managers_list_errors_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_ApplyUpdatesToInstances_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_ListErrors_sync", "segments": [ { - "end": 53, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 54, "start": 27, "type": "SHORT" }, @@ -38504,12 +40008,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 54, + "end": 55, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_apply_updates_to_instances_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_list_errors_sync.py" }, { "canonical": true, @@ -38518,19 +40022,19 @@ "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.create_instances", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.list_managed_instances", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.CreateInstances", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.ListManagedInstances", "service": { "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "CreateInstances" + "shortName": "ListManagedInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.CreateInstancesRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1.types.ListManagedInstancesRegionInstanceGroupManagersRequest" }, { "name": "project", @@ -38544,10 +40048,6 @@ "name": "instance_group_manager", "type": "str" }, - { - "name": "region_instance_group_managers_create_instances_request_resource", - "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagersCreateInstancesRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -38561,22 +40061,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "create_instances" + "resultType": "google.cloud.compute_v1.services.region_instance_group_managers.pagers.ListManagedInstancesPager", + "shortName": "list_managed_instances" }, - "description": "Sample for CreateInstances", - "file": "compute_v1_generated_region_instance_group_managers_create_instances_sync.py", + "description": "Sample for ListManagedInstances", + "file": "compute_v1_generated_region_instance_group_managers_list_managed_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_CreateInstances_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_ListManagedInstances_sync", "segments": [ { - "end": 53, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 54, "start": 27, "type": "SHORT" }, @@ -38596,12 +40096,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 54, + "end": 55, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_create_instances_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_list_managed_instances_sync.py" }, { "canonical": true, @@ -38610,19 +40110,19 @@ "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.delete_instances", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.list_per_instance_configs", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.DeleteInstances", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.ListPerInstanceConfigs", "service": { "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "DeleteInstances" + "shortName": "ListPerInstanceConfigs" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteInstancesRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1.types.ListPerInstanceConfigsRegionInstanceGroupManagersRequest" }, { "name": "project", @@ -38637,8 +40137,88 @@ "type": "str" }, { - "name": "region_instance_group_managers_delete_instances_request_resource", - "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagersDeleteInstancesRequest" + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.compute_v1.services.region_instance_group_managers.pagers.ListPerInstanceConfigsPager", + "shortName": "list_per_instance_configs" + }, + "description": "Sample for ListPerInstanceConfigs", + "file": "compute_v1_generated_region_instance_group_managers_list_per_instance_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_ListPerInstanceConfigs_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_region_instance_group_managers_list_per_instance_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", + "shortName": "RegionInstanceGroupManagersClient" + }, + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.list", + "method": { + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.List", + "service": { + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", + "shortName": "RegionInstanceGroupManagers" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ListRegionInstanceGroupManagersRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" }, { "name": "retry", @@ -38653,14 +40233,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete_instances" + "resultType": "google.cloud.compute_v1.services.region_instance_group_managers.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for DeleteInstances", - "file": "compute_v1_generated_region_instance_group_managers_delete_instances_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_region_instance_group_managers_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_DeleteInstances_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_List_sync", "segments": [ { "end": 53, @@ -38678,22 +40258,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 51, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_delete_instances_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_list_sync.py" }, { "canonical": true, @@ -38702,19 +40282,19 @@ "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.delete_per_instance_configs", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.patch_per_instance_configs", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.DeletePerInstanceConfigs", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.PatchPerInstanceConfigs", "service": { "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "DeletePerInstanceConfigs" + "shortName": "PatchPerInstanceConfigs" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeletePerInstanceConfigsRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1.types.PatchPerInstanceConfigsRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -38729,8 +40309,8 @@ "type": "str" }, { - "name": "region_instance_group_manager_delete_instance_config_req_resource", - "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagerDeleteInstanceConfigReq" + "name": "region_instance_group_manager_patch_instance_config_req_resource", + "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagerPatchInstanceConfigReq" }, { "name": "retry", @@ -38746,13 +40326,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete_per_instance_configs" + "shortName": "patch_per_instance_configs" }, - "description": "Sample for DeletePerInstanceConfigs", - "file": "compute_v1_generated_region_instance_group_managers_delete_per_instance_configs_sync.py", + "description": "Sample for PatchPerInstanceConfigs", + "file": "compute_v1_generated_region_instance_group_managers_patch_per_instance_configs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_DeletePerInstanceConfigs_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_PatchPerInstanceConfigs_sync", "segments": [ { "end": 53, @@ -38785,7 +40365,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_delete_per_instance_configs_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_patch_per_instance_configs_sync.py" }, { "canonical": true, @@ -38794,19 +40374,19 @@ "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.delete", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.patch", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.Delete", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.Patch", "service": { "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "Delete" + "shortName": "Patch" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1.types.PatchRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -38820,6 +40400,10 @@ "name": "instance_group_manager", "type": "str" }, + { + "name": "instance_group_manager_resource", + "type": "google.cloud.compute_v1.types.InstanceGroupManager" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -38834,13 +40418,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "shortName": "patch" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_region_instance_group_managers_delete_sync.py", + "description": "Sample for Patch", + "file": "compute_v1_generated_region_instance_group_managers_patch_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_Delete_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_Patch_sync", "segments": [ { "end": 53, @@ -38873,7 +40457,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_delete_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_patch_sync.py" }, { "canonical": true, @@ -38882,19 +40466,19 @@ "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.get", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.recreate_instances", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.Get", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.RecreateInstances", "service": { "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "Get" + "shortName": "RecreateInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1.types.RecreateInstancesRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -38908,6 +40492,10 @@ "name": "instance_group_manager", "type": "str" }, + { + "name": "region_instance_group_managers_recreate_request_resource", + "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagersRecreateRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -38921,14 +40509,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.InstanceGroupManager", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "recreate_instances" }, - "description": "Sample for Get", - "file": "compute_v1_generated_region_instance_group_managers_get_sync.py", + "description": "Sample for RecreateInstances", + "file": "compute_v1_generated_region_instance_group_managers_recreate_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_Get_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_RecreateInstances_sync", "segments": [ { "end": 53, @@ -38961,7 +40549,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_get_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_recreate_instances_sync.py" }, { "canonical": true, @@ -38970,19 +40558,19 @@ "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.insert", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.resize", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.Insert", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.Resize", "service": { "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "Insert" + "shortName": "Resize" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1.types.ResizeRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -38993,8 +40581,12 @@ "type": "str" }, { - "name": "instance_group_manager_resource", - "type": "google.cloud.compute_v1.types.InstanceGroupManager" + "name": "instance_group_manager", + "type": "str" + }, + { + "name": "size", + "type": "int" }, { "name": "retry", @@ -39010,21 +40602,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "shortName": "resize" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_region_instance_group_managers_insert_sync.py", + "description": "Sample for Resize", + "file": "compute_v1_generated_region_instance_group_managers_resize_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_Insert_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_Resize_sync", "segments": [ { - "end": 52, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 54, "start": 27, "type": "SHORT" }, @@ -39034,22 +40626,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_insert_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_resize_sync.py" }, { "canonical": true, @@ -39058,19 +40650,19 @@ "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.list_errors", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.set_instance_template", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.ListErrors", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.SetInstanceTemplate", "service": { "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "ListErrors" + "shortName": "SetInstanceTemplate" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListErrorsRegionInstanceGroupManagersRequest" + "type": "google.cloud.compute_v1.types.SetInstanceTemplateRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -39084,6 +40676,10 @@ "name": "instance_group_manager", "type": "str" }, + { + "name": "region_instance_group_managers_set_template_request_resource", + "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagersSetTemplateRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -39097,22 +40693,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.region_instance_group_managers.pagers.ListErrorsPager", - "shortName": "list_errors" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "set_instance_template" }, - "description": "Sample for ListErrors", - "file": "compute_v1_generated_region_instance_group_managers_list_errors_sync.py", + "description": "Sample for SetInstanceTemplate", + "file": "compute_v1_generated_region_instance_group_managers_set_instance_template_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_ListErrors_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_SetInstanceTemplate_sync", "segments": [ { - "end": 54, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 53, "start": 27, "type": "SHORT" }, @@ -39132,12 +40728,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 55, + "end": 54, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_list_errors_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_set_instance_template_sync.py" }, { "canonical": true, @@ -39146,19 +40742,19 @@ "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.list_managed_instances", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.set_target_pools", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.ListManagedInstances", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.SetTargetPools", "service": { "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "ListManagedInstances" + "shortName": "SetTargetPools" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListManagedInstancesRegionInstanceGroupManagersRequest" + "type": "google.cloud.compute_v1.types.SetTargetPoolsRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -39172,6 +40768,10 @@ "name": "instance_group_manager", "type": "str" }, + { + "name": "region_instance_group_managers_set_target_pools_request_resource", + "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagersSetTargetPoolsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -39185,22 +40785,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.region_instance_group_managers.pagers.ListManagedInstancesPager", - "shortName": "list_managed_instances" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "set_target_pools" }, - "description": "Sample for ListManagedInstances", - "file": "compute_v1_generated_region_instance_group_managers_list_managed_instances_sync.py", + "description": "Sample for SetTargetPools", + "file": "compute_v1_generated_region_instance_group_managers_set_target_pools_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_ListManagedInstances_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_SetTargetPools_sync", "segments": [ { - "end": 54, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 53, "start": 27, "type": "SHORT" }, @@ -39220,12 +40820,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 55, + "end": 54, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_list_managed_instances_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_set_target_pools_sync.py" }, { "canonical": true, @@ -39234,19 +40834,19 @@ "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", "shortName": "RegionInstanceGroupManagersClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.list_per_instance_configs", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.update_per_instance_configs", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.ListPerInstanceConfigs", + "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.UpdatePerInstanceConfigs", "service": { "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", "shortName": "RegionInstanceGroupManagers" }, - "shortName": "ListPerInstanceConfigs" + "shortName": "UpdatePerInstanceConfigs" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListPerInstanceConfigsRegionInstanceGroupManagersRequest" + "type": "google.cloud.compute_v1.types.UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest" }, { "name": "project", @@ -39260,6 +40860,10 @@ "name": "instance_group_manager", "type": "str" }, + { + "name": "region_instance_group_manager_update_instance_config_req_resource", + "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagerUpdateInstanceConfigReq" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -39273,22 +40877,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.region_instance_group_managers.pagers.ListPerInstanceConfigsPager", - "shortName": "list_per_instance_configs" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "update_per_instance_configs" }, - "description": "Sample for ListPerInstanceConfigs", - "file": "compute_v1_generated_region_instance_group_managers_list_per_instance_configs_sync.py", + "description": "Sample for UpdatePerInstanceConfigs", + "file": "compute_v1_generated_region_instance_group_managers_update_per_instance_configs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_ListPerInstanceConfigs_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_UpdatePerInstanceConfigs_sync", "segments": [ { - "end": 54, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 53, "start": 27, "type": "SHORT" }, @@ -39308,33 +40912,33 @@ "type": "REQUEST_EXECUTION" }, { - "end": 55, + "end": 54, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_list_per_instance_configs_sync.py" + "title": "compute_v1_generated_region_instance_group_managers_update_per_instance_configs_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", - "shortName": "RegionInstanceGroupManagersClient" + "fullName": "google.cloud.compute_v1.RegionInstanceGroupsClient", + "shortName": "RegionInstanceGroupsClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.list", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupsClient.get", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.List", + "fullName": "google.cloud.compute.v1.RegionInstanceGroups.Get", "service": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", - "shortName": "RegionInstanceGroupManagers" + "fullName": "google.cloud.compute.v1.RegionInstanceGroups", + "shortName": "RegionInstanceGroups" }, - "shortName": "List" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListRegionInstanceGroupManagersRequest" + "type": "google.cloud.compute_v1.types.GetRegionInstanceGroupRequest" }, { "name": "project", @@ -39344,6 +40948,10 @@ "name": "region", "type": "str" }, + { + "name": "instance_group", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -39357,14 +40965,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.region_instance_group_managers.pagers.ListPager", - "shortName": "list" + "resultType": "google.cloud.compute_v1.types.InstanceGroup", + "shortName": "get" }, - "description": "Sample for List", - "file": "compute_v1_generated_region_instance_group_managers_list_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_region_instance_groups_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_List_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroups_Get_sync", "segments": [ { "end": 53, @@ -39382,43 +40990,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 50, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_list_sync.py" + "title": "compute_v1_generated_region_instance_groups_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", - "shortName": "RegionInstanceGroupManagersClient" + "fullName": "google.cloud.compute_v1.RegionInstanceGroupsClient", + "shortName": "RegionInstanceGroupsClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.patch_per_instance_configs", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupsClient.list_instances", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.PatchPerInstanceConfigs", + "fullName": "google.cloud.compute.v1.RegionInstanceGroups.ListInstances", "service": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", - "shortName": "RegionInstanceGroupManagers" + "fullName": "google.cloud.compute.v1.RegionInstanceGroups", + "shortName": "RegionInstanceGroups" }, - "shortName": "PatchPerInstanceConfigs" + "shortName": "ListInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchPerInstanceConfigsRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1.types.ListInstancesRegionInstanceGroupsRequest" }, { "name": "project", @@ -39429,12 +41037,12 @@ "type": "str" }, { - "name": "instance_group_manager", + "name": "instance_group", "type": "str" }, { - "name": "region_instance_group_manager_patch_instance_config_req_resource", - "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagerPatchInstanceConfigReq" + "name": "region_instance_groups_list_instances_request_resource", + "type": "google.cloud.compute_v1.types.RegionInstanceGroupsListInstancesRequest" }, { "name": "retry", @@ -39449,22 +41057,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch_per_instance_configs" + "resultType": "google.cloud.compute_v1.services.region_instance_groups.pagers.ListInstancesPager", + "shortName": "list_instances" }, - "description": "Sample for PatchPerInstanceConfigs", - "file": "compute_v1_generated_region_instance_group_managers_patch_per_instance_configs_sync.py", + "description": "Sample for ListInstances", + "file": "compute_v1_generated_region_instance_groups_list_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_PatchPerInstanceConfigs_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroups_ListInstances_sync", "segments": [ { - "end": 53, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 54, "start": 27, "type": "SHORT" }, @@ -39484,33 +41092,33 @@ "type": "REQUEST_EXECUTION" }, { - "end": 54, + "end": 55, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_patch_per_instance_configs_sync.py" + "title": "compute_v1_generated_region_instance_groups_list_instances_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", - "shortName": "RegionInstanceGroupManagersClient" + "fullName": "google.cloud.compute_v1.RegionInstanceGroupsClient", + "shortName": "RegionInstanceGroupsClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.patch", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupsClient.list", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.Patch", + "fullName": "google.cloud.compute.v1.RegionInstanceGroups.List", "service": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", - "shortName": "RegionInstanceGroupManagers" + "fullName": "google.cloud.compute.v1.RegionInstanceGroups", + "shortName": "RegionInstanceGroups" }, - "shortName": "Patch" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.PatchRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1.types.ListRegionInstanceGroupsRequest" }, { "name": "project", @@ -39520,14 +41128,6 @@ "name": "region", "type": "str" }, - { - "name": "instance_group_manager", - "type": "str" - }, - { - "name": "instance_group_manager_resource", - "type": "google.cloud.compute_v1.types.InstanceGroupManager" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -39541,14 +41141,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "resultType": "google.cloud.compute_v1.services.region_instance_groups.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Patch", - "file": "compute_v1_generated_region_instance_group_managers_patch_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_region_instance_groups_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_Patch_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroups_List_sync", "segments": [ { "end": 53, @@ -39566,43 +41166,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 51, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_patch_sync.py" + "title": "compute_v1_generated_region_instance_groups_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", - "shortName": "RegionInstanceGroupManagersClient" + "fullName": "google.cloud.compute_v1.RegionInstanceGroupsClient", + "shortName": "RegionInstanceGroupsClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.recreate_instances", + "fullName": "google.cloud.compute_v1.RegionInstanceGroupsClient.set_named_ports", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.RecreateInstances", + "fullName": "google.cloud.compute.v1.RegionInstanceGroups.SetNamedPorts", "service": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", - "shortName": "RegionInstanceGroupManagers" + "fullName": "google.cloud.compute.v1.RegionInstanceGroups", + "shortName": "RegionInstanceGroups" }, - "shortName": "RecreateInstances" + "shortName": "SetNamedPorts" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.RecreateInstancesRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1.types.SetNamedPortsRegionInstanceGroupRequest" }, { "name": "project", @@ -39613,12 +41213,12 @@ "type": "str" }, { - "name": "instance_group_manager", + "name": "instance_group", "type": "str" }, { - "name": "region_instance_group_managers_recreate_request_resource", - "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagersRecreateRequest" + "name": "region_instance_groups_set_named_ports_request_resource", + "type": "google.cloud.compute_v1.types.RegionInstanceGroupsSetNamedPortsRequest" }, { "name": "retry", @@ -39634,13 +41234,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "recreate_instances" + "shortName": "set_named_ports" }, - "description": "Sample for RecreateInstances", - "file": "compute_v1_generated_region_instance_group_managers_recreate_instances_sync.py", + "description": "Sample for SetNamedPorts", + "file": "compute_v1_generated_region_instance_groups_set_named_ports_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_RecreateInstances_sync", + "regionTag": "compute_v1_generated_RegionInstanceGroups_SetNamedPorts_sync", "segments": [ { "end": 53, @@ -39673,28 +41273,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_recreate_instances_sync.py" + "title": "compute_v1_generated_region_instance_groups_set_named_ports_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", - "shortName": "RegionInstanceGroupManagersClient" + "fullName": "google.cloud.compute_v1.RegionInstanceTemplatesClient", + "shortName": "RegionInstanceTemplatesClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.resize", + "fullName": "google.cloud.compute_v1.RegionInstanceTemplatesClient.delete", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.Resize", + "fullName": "google.cloud.compute.v1.RegionInstanceTemplates.Delete", "service": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", - "shortName": "RegionInstanceGroupManagers" + "fullName": "google.cloud.compute.v1.RegionInstanceTemplates", + "shortName": "RegionInstanceTemplates" }, - "shortName": "Resize" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ResizeRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1.types.DeleteRegionInstanceTemplateRequest" }, { "name": "project", @@ -39705,13 +41305,9 @@ "type": "str" }, { - "name": "instance_group_manager", + "name": "instance_template", "type": "str" }, - { - "name": "size", - "type": "int" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -39726,21 +41322,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "resize" + "shortName": "delete" }, - "description": "Sample for Resize", - "file": "compute_v1_generated_region_instance_group_managers_resize_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_region_instance_templates_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_Resize_sync", + "regionTag": "compute_v1_generated_RegionInstanceTemplates_Delete_sync", "segments": [ { - "end": 54, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 53, "start": 27, "type": "SHORT" }, @@ -39750,43 +41346,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_resize_sync.py" + "title": "compute_v1_generated_region_instance_templates_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", - "shortName": "RegionInstanceGroupManagersClient" + "fullName": "google.cloud.compute_v1.RegionInstanceTemplatesClient", + "shortName": "RegionInstanceTemplatesClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.set_instance_template", + "fullName": "google.cloud.compute_v1.RegionInstanceTemplatesClient.get", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.SetInstanceTemplate", + "fullName": "google.cloud.compute.v1.RegionInstanceTemplates.Get", "service": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", - "shortName": "RegionInstanceGroupManagers" + "fullName": "google.cloud.compute.v1.RegionInstanceTemplates", + "shortName": "RegionInstanceTemplates" }, - "shortName": "SetInstanceTemplate" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetInstanceTemplateRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1.types.GetRegionInstanceTemplateRequest" }, { "name": "project", @@ -39797,13 +41393,9 @@ "type": "str" }, { - "name": "instance_group_manager", + "name": "instance_template", "type": "str" }, - { - "name": "region_instance_group_managers_set_template_request_resource", - "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagersSetTemplateRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -39817,14 +41409,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_instance_template" + "resultType": "google.cloud.compute_v1.types.InstanceTemplate", + "shortName": "get" }, - "description": "Sample for SetInstanceTemplate", - "file": "compute_v1_generated_region_instance_group_managers_set_instance_template_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_region_instance_templates_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_SetInstanceTemplate_sync", + "regionTag": "compute_v1_generated_RegionInstanceTemplates_Get_sync", "segments": [ { "end": 53, @@ -39857,28 +41449,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_set_instance_template_sync.py" + "title": "compute_v1_generated_region_instance_templates_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", - "shortName": "RegionInstanceGroupManagersClient" + "fullName": "google.cloud.compute_v1.RegionInstanceTemplatesClient", + "shortName": "RegionInstanceTemplatesClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.set_target_pools", + "fullName": "google.cloud.compute_v1.RegionInstanceTemplatesClient.insert", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.SetTargetPools", + "fullName": "google.cloud.compute.v1.RegionInstanceTemplates.Insert", "service": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", - "shortName": "RegionInstanceGroupManagers" + "fullName": "google.cloud.compute.v1.RegionInstanceTemplates", + "shortName": "RegionInstanceTemplates" }, - "shortName": "SetTargetPools" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetTargetPoolsRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1.types.InsertRegionInstanceTemplateRequest" }, { "name": "project", @@ -39889,12 +41481,8 @@ "type": "str" }, { - "name": "instance_group_manager", - "type": "str" - }, - { - "name": "region_instance_group_managers_set_target_pools_request_resource", - "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagersSetTargetPoolsRequest" + "name": "instance_template_resource", + "type": "google.cloud.compute_v1.types.InstanceTemplate" }, { "name": "retry", @@ -39910,21 +41498,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_target_pools" + "shortName": "insert" }, - "description": "Sample for SetTargetPools", - "file": "compute_v1_generated_region_instance_group_managers_set_target_pools_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_region_instance_templates_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_SetTargetPools_sync", + "regionTag": "compute_v1_generated_RegionInstanceTemplates_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -39934,43 +41522,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_set_target_pools_sync.py" + "title": "compute_v1_generated_region_instance_templates_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient", - "shortName": "RegionInstanceGroupManagersClient" + "fullName": "google.cloud.compute_v1.RegionInstanceTemplatesClient", + "shortName": "RegionInstanceTemplatesClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupManagersClient.update_per_instance_configs", + "fullName": "google.cloud.compute_v1.RegionInstanceTemplatesClient.list", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers.UpdatePerInstanceConfigs", + "fullName": "google.cloud.compute.v1.RegionInstanceTemplates.List", "service": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroupManagers", - "shortName": "RegionInstanceGroupManagers" + "fullName": "google.cloud.compute.v1.RegionInstanceTemplates", + "shortName": "RegionInstanceTemplates" }, - "shortName": "UpdatePerInstanceConfigs" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest" + "type": "google.cloud.compute_v1.types.ListRegionInstanceTemplatesRequest" }, { "name": "project", @@ -39980,14 +41568,6 @@ "name": "region", "type": "str" }, - { - "name": "instance_group_manager", - "type": "str" - }, - { - "name": "region_instance_group_manager_update_instance_config_req_resource", - "type": "google.cloud.compute_v1.types.RegionInstanceGroupManagerUpdateInstanceConfigReq" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -40001,14 +41581,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "update_per_instance_configs" + "resultType": "google.cloud.compute_v1.services.region_instance_templates.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for UpdatePerInstanceConfigs", - "file": "compute_v1_generated_region_instance_group_managers_update_per_instance_configs_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_region_instance_templates_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroupManagers_UpdatePerInstanceConfigs_sync", + "regionTag": "compute_v1_generated_RegionInstanceTemplates_List_sync", "segments": [ { "end": 53, @@ -40026,43 +41606,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 51, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_group_managers_update_per_instance_configs_sync.py" + "title": "compute_v1_generated_region_instance_templates_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstanceGroupsClient", - "shortName": "RegionInstanceGroupsClient" + "fullName": "google.cloud.compute_v1.RegionInstancesClient", + "shortName": "RegionInstancesClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupsClient.get", + "fullName": "google.cloud.compute_v1.RegionInstancesClient.bulk_insert", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroups.Get", + "fullName": "google.cloud.compute.v1.RegionInstances.BulkInsert", "service": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroups", - "shortName": "RegionInstanceGroups" + "fullName": "google.cloud.compute.v1.RegionInstances", + "shortName": "RegionInstances" }, - "shortName": "Get" + "shortName": "BulkInsert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetRegionInstanceGroupRequest" + "type": "google.cloud.compute_v1.types.BulkInsertRegionInstanceRequest" }, { "name": "project", @@ -40073,8 +41653,8 @@ "type": "str" }, { - "name": "instance_group", - "type": "str" + "name": "bulk_insert_instance_resource_resource", + "type": "google.cloud.compute_v1.types.BulkInsertInstanceResource" }, { "name": "retry", @@ -40089,22 +41669,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.InstanceGroup", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "bulk_insert" }, - "description": "Sample for Get", - "file": "compute_v1_generated_region_instance_groups_get_sync.py", + "description": "Sample for BulkInsert", + "file": "compute_v1_generated_region_instances_bulk_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroups_Get_sync", + "regionTag": "compute_v1_generated_RegionInstances_BulkInsert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -40114,43 +41694,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_groups_get_sync.py" + "title": "compute_v1_generated_region_instances_bulk_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstanceGroupsClient", - "shortName": "RegionInstanceGroupsClient" + "fullName": "google.cloud.compute_v1.RegionInstantSnapshotsClient", + "shortName": "RegionInstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupsClient.list_instances", + "fullName": "google.cloud.compute_v1.RegionInstantSnapshotsClient.delete", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroups.ListInstances", + "fullName": "google.cloud.compute.v1.RegionInstantSnapshots.Delete", "service": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroups", - "shortName": "RegionInstanceGroups" + "fullName": "google.cloud.compute.v1.RegionInstantSnapshots", + "shortName": "RegionInstantSnapshots" }, - "shortName": "ListInstances" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListInstancesRegionInstanceGroupsRequest" + "type": "google.cloud.compute_v1.types.DeleteRegionInstantSnapshotRequest" }, { "name": "project", @@ -40161,13 +41741,9 @@ "type": "str" }, { - "name": "instance_group", + "name": "instant_snapshot", "type": "str" }, - { - "name": "region_instance_groups_list_instances_request_resource", - "type": "google.cloud.compute_v1.types.RegionInstanceGroupsListInstancesRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -40181,22 +41757,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.region_instance_groups.pagers.ListInstancesPager", - "shortName": "list_instances" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for ListInstances", - "file": "compute_v1_generated_region_instance_groups_list_instances_sync.py", + "description": "Sample for Delete", + "file": "compute_v1_generated_region_instant_snapshots_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroups_ListInstances_sync", + "regionTag": "compute_v1_generated_RegionInstantSnapshots_Delete_sync", "segments": [ { - "end": 54, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 53, "start": 27, "type": "SHORT" }, @@ -40216,33 +41792,33 @@ "type": "REQUEST_EXECUTION" }, { - "end": 55, + "end": 54, "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_groups_list_instances_sync.py" + "title": "compute_v1_generated_region_instant_snapshots_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstanceGroupsClient", - "shortName": "RegionInstanceGroupsClient" + "fullName": "google.cloud.compute_v1.RegionInstantSnapshotsClient", + "shortName": "RegionInstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupsClient.list", + "fullName": "google.cloud.compute_v1.RegionInstantSnapshotsClient.get_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroups.List", + "fullName": "google.cloud.compute.v1.RegionInstantSnapshots.GetIamPolicy", "service": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroups", - "shortName": "RegionInstanceGroups" + "fullName": "google.cloud.compute.v1.RegionInstantSnapshots", + "shortName": "RegionInstantSnapshots" }, - "shortName": "List" + "shortName": "GetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListRegionInstanceGroupsRequest" + "type": "google.cloud.compute_v1.types.GetIamPolicyRegionInstantSnapshotRequest" }, { "name": "project", @@ -40252,6 +41828,10 @@ "name": "region", "type": "str" }, + { + "name": "resource", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -40265,14 +41845,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.region_instance_groups.pagers.ListPager", - "shortName": "list" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "get_iam_policy" }, - "description": "Sample for List", - "file": "compute_v1_generated_region_instance_groups_list_sync.py", + "description": "Sample for GetIamPolicy", + "file": "compute_v1_generated_region_instant_snapshots_get_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroups_List_sync", + "regionTag": "compute_v1_generated_RegionInstantSnapshots_GetIamPolicy_sync", "segments": [ { "end": 53, @@ -40290,43 +41870,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 50, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_groups_list_sync.py" + "title": "compute_v1_generated_region_instant_snapshots_get_iam_policy_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstanceGroupsClient", - "shortName": "RegionInstanceGroupsClient" + "fullName": "google.cloud.compute_v1.RegionInstantSnapshotsClient", + "shortName": "RegionInstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceGroupsClient.set_named_ports", + "fullName": "google.cloud.compute_v1.RegionInstantSnapshotsClient.get", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroups.SetNamedPorts", + "fullName": "google.cloud.compute.v1.RegionInstantSnapshots.Get", "service": { - "fullName": "google.cloud.compute.v1.RegionInstanceGroups", - "shortName": "RegionInstanceGroups" + "fullName": "google.cloud.compute.v1.RegionInstantSnapshots", + "shortName": "RegionInstantSnapshots" }, - "shortName": "SetNamedPorts" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.SetNamedPortsRegionInstanceGroupRequest" + "type": "google.cloud.compute_v1.types.GetRegionInstantSnapshotRequest" }, { "name": "project", @@ -40337,13 +41917,9 @@ "type": "str" }, { - "name": "instance_group", + "name": "instant_snapshot", "type": "str" }, - { - "name": "region_instance_groups_set_named_ports_request_resource", - "type": "google.cloud.compute_v1.types.RegionInstanceGroupsSetNamedPortsRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -40357,14 +41933,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "set_named_ports" + "resultType": "google.cloud.compute_v1.types.InstantSnapshot", + "shortName": "get" }, - "description": "Sample for SetNamedPorts", - "file": "compute_v1_generated_region_instance_groups_set_named_ports_sync.py", + "description": "Sample for Get", + "file": "compute_v1_generated_region_instant_snapshots_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceGroups_SetNamedPorts_sync", + "regionTag": "compute_v1_generated_RegionInstantSnapshots_Get_sync", "segments": [ { "end": 53, @@ -40397,28 +41973,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_groups_set_named_ports_sync.py" + "title": "compute_v1_generated_region_instant_snapshots_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstanceTemplatesClient", - "shortName": "RegionInstanceTemplatesClient" + "fullName": "google.cloud.compute_v1.RegionInstantSnapshotsClient", + "shortName": "RegionInstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceTemplatesClient.delete", + "fullName": "google.cloud.compute_v1.RegionInstantSnapshotsClient.insert", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceTemplates.Delete", + "fullName": "google.cloud.compute.v1.RegionInstantSnapshots.Insert", "service": { - "fullName": "google.cloud.compute.v1.RegionInstanceTemplates", - "shortName": "RegionInstanceTemplates" + "fullName": "google.cloud.compute.v1.RegionInstantSnapshots", + "shortName": "RegionInstantSnapshots" }, - "shortName": "Delete" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteRegionInstanceTemplateRequest" + "type": "google.cloud.compute_v1.types.InsertRegionInstantSnapshotRequest" }, { "name": "project", @@ -40429,8 +42005,8 @@ "type": "str" }, { - "name": "instance_template", - "type": "str" + "name": "instant_snapshot_resource", + "type": "google.cloud.compute_v1.types.InstantSnapshot" }, { "name": "retry", @@ -40446,21 +42022,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "shortName": "insert" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_region_instance_templates_delete_sync.py", + "description": "Sample for Insert", + "file": "compute_v1_generated_region_instant_snapshots_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceTemplates_Delete_sync", + "regionTag": "compute_v1_generated_RegionInstantSnapshots_Insert_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -40470,43 +42046,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_templates_delete_sync.py" + "title": "compute_v1_generated_region_instant_snapshots_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstanceTemplatesClient", - "shortName": "RegionInstanceTemplatesClient" + "fullName": "google.cloud.compute_v1.RegionInstantSnapshotsClient", + "shortName": "RegionInstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceTemplatesClient.get", + "fullName": "google.cloud.compute_v1.RegionInstantSnapshotsClient.list", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceTemplates.Get", + "fullName": "google.cloud.compute.v1.RegionInstantSnapshots.List", "service": { - "fullName": "google.cloud.compute.v1.RegionInstanceTemplates", - "shortName": "RegionInstanceTemplates" + "fullName": "google.cloud.compute.v1.RegionInstantSnapshots", + "shortName": "RegionInstantSnapshots" }, - "shortName": "Get" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.GetRegionInstanceTemplateRequest" + "type": "google.cloud.compute_v1.types.ListRegionInstantSnapshotsRequest" }, { "name": "project", @@ -40516,10 +42092,6 @@ "name": "region", "type": "str" }, - { - "name": "instance_template", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -40533,14 +42105,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.types.InstanceTemplate", - "shortName": "get" + "resultType": "google.cloud.compute_v1.services.region_instant_snapshots.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Get", - "file": "compute_v1_generated_region_instance_templates_get_sync.py", + "description": "Sample for List", + "file": "compute_v1_generated_region_instant_snapshots_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceTemplates_Get_sync", + "regionTag": "compute_v1_generated_RegionInstantSnapshots_List_sync", "segments": [ { "end": 53, @@ -40558,43 +42130,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 51, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_templates_get_sync.py" + "title": "compute_v1_generated_region_instant_snapshots_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstanceTemplatesClient", - "shortName": "RegionInstanceTemplatesClient" + "fullName": "google.cloud.compute_v1.RegionInstantSnapshotsClient", + "shortName": "RegionInstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceTemplatesClient.insert", + "fullName": "google.cloud.compute_v1.RegionInstantSnapshotsClient.set_iam_policy", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceTemplates.Insert", + "fullName": "google.cloud.compute.v1.RegionInstantSnapshots.SetIamPolicy", "service": { - "fullName": "google.cloud.compute.v1.RegionInstanceTemplates", - "shortName": "RegionInstanceTemplates" + "fullName": "google.cloud.compute.v1.RegionInstantSnapshots", + "shortName": "RegionInstantSnapshots" }, - "shortName": "Insert" + "shortName": "SetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.InsertRegionInstanceTemplateRequest" + "type": "google.cloud.compute_v1.types.SetIamPolicyRegionInstantSnapshotRequest" }, { "name": "project", @@ -40605,8 +42177,12 @@ "type": "str" }, { - "name": "instance_template_resource", - "type": "google.cloud.compute_v1.types.InstanceTemplate" + "name": "resource", + "type": "str" + }, + { + "name": "region_set_policy_request_resource", + "type": "google.cloud.compute_v1.types.RegionSetPolicyRequest" }, { "name": "retry", @@ -40621,22 +42197,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "resultType": "google.cloud.compute_v1.types.Policy", + "shortName": "set_iam_policy" }, - "description": "Sample for Insert", - "file": "compute_v1_generated_region_instance_templates_insert_sync.py", + "description": "Sample for SetIamPolicy", + "file": "compute_v1_generated_region_instant_snapshots_set_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceTemplates_Insert_sync", + "regionTag": "compute_v1_generated_RegionInstantSnapshots_SetIamPolicy_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -40646,43 +42222,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_templates_insert_sync.py" + "title": "compute_v1_generated_region_instant_snapshots_set_iam_policy_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstanceTemplatesClient", - "shortName": "RegionInstanceTemplatesClient" + "fullName": "google.cloud.compute_v1.RegionInstantSnapshotsClient", + "shortName": "RegionInstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.RegionInstanceTemplatesClient.list", + "fullName": "google.cloud.compute_v1.RegionInstantSnapshotsClient.set_labels", "method": { - "fullName": "google.cloud.compute.v1.RegionInstanceTemplates.List", + "fullName": "google.cloud.compute.v1.RegionInstantSnapshots.SetLabels", "service": { - "fullName": "google.cloud.compute.v1.RegionInstanceTemplates", - "shortName": "RegionInstanceTemplates" + "fullName": "google.cloud.compute.v1.RegionInstantSnapshots", + "shortName": "RegionInstantSnapshots" }, - "shortName": "List" + "shortName": "SetLabels" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.ListRegionInstanceTemplatesRequest" + "type": "google.cloud.compute_v1.types.SetLabelsRegionInstantSnapshotRequest" }, { "name": "project", @@ -40692,6 +42268,14 @@ "name": "region", "type": "str" }, + { + "name": "resource", + "type": "str" + }, + { + "name": "region_set_labels_request_resource", + "type": "google.cloud.compute_v1.types.RegionSetLabelsRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -40705,14 +42289,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.compute_v1.services.region_instance_templates.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "set_labels" }, - "description": "Sample for List", - "file": "compute_v1_generated_region_instance_templates_list_sync.py", + "description": "Sample for SetLabels", + "file": "compute_v1_generated_region_instant_snapshots_set_labels_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstanceTemplates_List_sync", + "regionTag": "compute_v1_generated_RegionInstantSnapshots_SetLabels_sync", "segments": [ { "end": 53, @@ -40730,43 +42314,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 50, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instance_templates_list_sync.py" + "title": "compute_v1_generated_region_instant_snapshots_set_labels_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1.RegionInstancesClient", - "shortName": "RegionInstancesClient" + "fullName": "google.cloud.compute_v1.RegionInstantSnapshotsClient", + "shortName": "RegionInstantSnapshotsClient" }, - "fullName": "google.cloud.compute_v1.RegionInstancesClient.bulk_insert", + "fullName": "google.cloud.compute_v1.RegionInstantSnapshotsClient.test_iam_permissions", "method": { - "fullName": "google.cloud.compute.v1.RegionInstances.BulkInsert", + "fullName": "google.cloud.compute.v1.RegionInstantSnapshots.TestIamPermissions", "service": { - "fullName": "google.cloud.compute.v1.RegionInstances", - "shortName": "RegionInstances" + "fullName": "google.cloud.compute.v1.RegionInstantSnapshots", + "shortName": "RegionInstantSnapshots" }, - "shortName": "BulkInsert" + "shortName": "TestIamPermissions" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.BulkInsertRegionInstanceRequest" + "type": "google.cloud.compute_v1.types.TestIamPermissionsRegionInstantSnapshotRequest" }, { "name": "project", @@ -40777,8 +42361,12 @@ "type": "str" }, { - "name": "bulk_insert_instance_resource_resource", - "type": "google.cloud.compute_v1.types.BulkInsertInstanceResource" + "name": "resource", + "type": "str" + }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1.types.TestPermissionsRequest" }, { "name": "retry", @@ -40793,22 +42381,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "bulk_insert" + "resultType": "google.cloud.compute_v1.types.TestPermissionsResponse", + "shortName": "test_iam_permissions" }, - "description": "Sample for BulkInsert", - "file": "compute_v1_generated_region_instances_bulk_insert_sync.py", + "description": "Sample for TestIamPermissions", + "file": "compute_v1_generated_region_instant_snapshots_test_iam_permissions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_RegionInstances_BulkInsert_sync", + "regionTag": "compute_v1_generated_RegionInstantSnapshots_TestIamPermissions_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -40818,22 +42406,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_region_instances_bulk_insert_sync.py" + "title": "compute_v1_generated_region_instant_snapshots_test_iam_permissions_sync.py" }, { "canonical": true, diff --git a/packages/google-cloud-compute/scripts/fixup_compute_v1_keywords.py b/packages/google-cloud-compute/scripts/fixup_compute_v1_keywords.py index 16da1fc79eef..95f5e409788b 100644 --- a/packages/google-cloud-compute/scripts/fixup_compute_v1_keywords.py +++ b/packages/google-cloud-compute/scripts/fixup_compute_v1_keywords.py @@ -131,6 +131,7 @@ class computeCallTransformer(cst.CSTTransformer): 'set_backend_service': ('project', 'target_ssl_proxies_set_backend_service_request_resource', 'target_ssl_proxy', 'request_id', ), 'set_backup': ('project', 'region', 'target_pool', 'target_reference_resource', 'failover_ratio', 'request_id', ), 'set_certificate_map': ('project', 'target_https_proxies_set_certificate_map_request_resource', 'target_https_proxy', 'request_id', ), + 'set_cloud_armor_tier': ('project', 'projects_set_cloud_armor_tier_request_resource', 'request_id', ), 'set_common_instance_metadata': ('metadata_resource', 'project', 'request_id', ), 'set_default_network_tier': ('project', 'projects_set_default_network_tier_request_resource', 'request_id', ), 'set_deletion_protection': ('project', 'resource', 'zone', 'deletion_protection', 'request_id', ), diff --git a/packages/google-cloud-compute/setup.py b/packages/google-cloud-compute/setup.py index e1c94199e81f..842a06af1508 100644 --- a/packages/google-cloud-compute/setup.py +++ b/packages/google-cloud-compute/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] 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 00577a93de11..82739903868f 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 @@ -3464,6 +3464,7 @@ def test_get_rest(request_type): security_policy="security_policy_value", self_link="self_link_value", service_bindings=["service_bindings_value"], + service_lb_policy="service_lb_policy_value", session_affinity="session_affinity_value", timeout_sec=1185, ) @@ -3504,6 +3505,7 @@ def test_get_rest(request_type): assert response.security_policy == "security_policy_value" assert response.self_link == "self_link_value" assert response.service_bindings == ["service_bindings_value"] + assert response.service_lb_policy == "service_lb_policy_value" assert response.session_affinity == "session_affinity_value" assert response.timeout_sec == 1185 @@ -4428,6 +4430,7 @@ def test_insert_rest(request_type): "max_rate_per_endpoint": 0.22310000000000002, "max_rate_per_instance": 0.22190000000000001, "max_utilization": 0.1633, + "preference": "preference_value", } ], "cdn_policy": { @@ -4569,6 +4572,7 @@ def test_insert_rest(request_type): }, "self_link": "self_link_value", "service_bindings": ["service_bindings_value1", "service_bindings_value2"], + "service_lb_policy": "service_lb_policy_value", "session_affinity": "session_affinity_value", "subsetting": {"policy": "policy_value"}, "timeout_sec": 1185, @@ -4983,6 +4987,7 @@ def test_insert_unary_rest(request_type): "max_rate_per_endpoint": 0.22310000000000002, "max_rate_per_instance": 0.22190000000000001, "max_utilization": 0.1633, + "preference": "preference_value", } ], "cdn_policy": { @@ -5124,6 +5129,7 @@ def test_insert_unary_rest(request_type): }, "self_link": "self_link_value", "service_bindings": ["service_bindings_value1", "service_bindings_value2"], + "service_lb_policy": "service_lb_policy_value", "session_affinity": "session_affinity_value", "subsetting": {"policy": "policy_value"}, "timeout_sec": 1185, @@ -6214,6 +6220,7 @@ def test_patch_rest(request_type): "max_rate_per_endpoint": 0.22310000000000002, "max_rate_per_instance": 0.22190000000000001, "max_utilization": 0.1633, + "preference": "preference_value", } ], "cdn_policy": { @@ -6355,6 +6362,7 @@ def test_patch_rest(request_type): }, "self_link": "self_link_value", "service_bindings": ["service_bindings_value1", "service_bindings_value2"], + "service_lb_policy": "service_lb_policy_value", "session_affinity": "session_affinity_value", "subsetting": {"policy": "policy_value"}, "timeout_sec": 1185, @@ -6776,6 +6784,7 @@ def test_patch_unary_rest(request_type): "max_rate_per_endpoint": 0.22310000000000002, "max_rate_per_instance": 0.22190000000000001, "max_utilization": 0.1633, + "preference": "preference_value", } ], "cdn_policy": { @@ -6917,6 +6926,7 @@ def test_patch_unary_rest(request_type): }, "self_link": "self_link_value", "service_bindings": ["service_bindings_value1", "service_bindings_value2"], + "service_lb_policy": "service_lb_policy_value", "session_affinity": "session_affinity_value", "subsetting": {"policy": "policy_value"}, "timeout_sec": 1185, @@ -9723,6 +9733,7 @@ def test_update_rest(request_type): "max_rate_per_endpoint": 0.22310000000000002, "max_rate_per_instance": 0.22190000000000001, "max_utilization": 0.1633, + "preference": "preference_value", } ], "cdn_policy": { @@ -9864,6 +9875,7 @@ def test_update_rest(request_type): }, "self_link": "self_link_value", "service_bindings": ["service_bindings_value1", "service_bindings_value2"], + "service_lb_policy": "service_lb_policy_value", "session_affinity": "session_affinity_value", "subsetting": {"policy": "policy_value"}, "timeout_sec": 1185, @@ -10285,6 +10297,7 @@ def test_update_unary_rest(request_type): "max_rate_per_endpoint": 0.22310000000000002, "max_rate_per_instance": 0.22190000000000001, "max_utilization": 0.1633, + "preference": "preference_value", } ], "cdn_policy": { @@ -10426,6 +10439,7 @@ def test_update_unary_rest(request_type): }, "self_link": "self_link_value", "service_bindings": ["service_bindings_value1", "service_bindings_value2"], + "service_lb_policy": "service_lb_policy_value", "session_affinity": "session_affinity_value", "subsetting": {"policy": "policy_value"}, "timeout_sec": 1185, 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 9d605f7e72ba..090d41684e09 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 @@ -2924,6 +2924,9 @@ def test_create_snapshot_rest(request_type): "source_disk_encryption_key": {}, "source_disk_for_recovery_checkpoint": "source_disk_for_recovery_checkpoint_value", "source_disk_id": "source_disk_id_value", + "source_instant_snapshot": "source_instant_snapshot_value", + "source_instant_snapshot_encryption_key": {}, + "source_instant_snapshot_id": "source_instant_snapshot_id_value", "source_snapshot_schedule_policy": "source_snapshot_schedule_policy_value", "source_snapshot_schedule_policy_id": "source_snapshot_schedule_policy_id_value", "status": "status_value", @@ -3374,6 +3377,9 @@ def test_create_snapshot_unary_rest(request_type): "source_disk_encryption_key": {}, "source_disk_for_recovery_checkpoint": "source_disk_for_recovery_checkpoint_value", "source_disk_id": "source_disk_id_value", + "source_instant_snapshot": "source_instant_snapshot_value", + "source_instant_snapshot_encryption_key": {}, + "source_instant_snapshot_id": "source_instant_snapshot_id_value", "source_snapshot_schedule_policy": "source_snapshot_schedule_policy_value", "source_snapshot_schedule_policy_id": "source_snapshot_schedule_policy_id_value", "status": "status_value", @@ -4430,6 +4436,8 @@ def test_get_rest(request_type): source_disk_id="source_disk_id_value", source_image="source_image_value", source_image_id="source_image_id_value", + source_instant_snapshot="source_instant_snapshot_value", + source_instant_snapshot_id="source_instant_snapshot_id_value", source_snapshot="source_snapshot_value", source_snapshot_id="source_snapshot_id_value", source_storage_object="source_storage_object_value", @@ -4488,6 +4496,8 @@ def test_get_rest(request_type): assert response.source_disk_id == "source_disk_id_value" assert response.source_image == "source_image_value" assert response.source_image_id == "source_image_id_value" + assert response.source_instant_snapshot == "source_instant_snapshot_value" + assert response.source_instant_snapshot_id == "source_instant_snapshot_id_value" assert response.source_snapshot == "source_snapshot_value" assert response.source_snapshot_id == "source_snapshot_id_value" assert response.source_storage_object == "source_storage_object_value" @@ -5099,6 +5109,8 @@ def test_insert_rest(request_type): "source_image": "source_image_value", "source_image_encryption_key": {}, "source_image_id": "source_image_id_value", + "source_instant_snapshot": "source_instant_snapshot_value", + "source_instant_snapshot_id": "source_instant_snapshot_id_value", "source_snapshot": "source_snapshot_value", "source_snapshot_encryption_key": {}, "source_snapshot_id": "source_snapshot_id_value", @@ -5559,6 +5571,8 @@ def test_insert_unary_rest(request_type): "source_image": "source_image_value", "source_image_encryption_key": {}, "source_image_id": "source_image_id_value", + "source_instant_snapshot": "source_instant_snapshot_value", + "source_instant_snapshot_id": "source_instant_snapshot_id_value", "source_snapshot": "source_snapshot_value", "source_snapshot_encryption_key": {}, "source_snapshot_id": "source_snapshot_id_value", @@ -11851,6 +11865,8 @@ def test_update_rest(request_type): "source_image": "source_image_value", "source_image_encryption_key": {}, "source_image_id": "source_image_id_value", + "source_instant_snapshot": "source_instant_snapshot_value", + "source_instant_snapshot_id": "source_instant_snapshot_id_value", "source_snapshot": "source_snapshot_value", "source_snapshot_encryption_key": {}, "source_snapshot_id": "source_snapshot_id_value", @@ -12320,6 +12336,8 @@ def test_update_unary_rest(request_type): "source_image": "source_image_value", "source_image_encryption_key": {}, "source_image_id": "source_image_id_value", + "source_instant_snapshot": "source_instant_snapshot_value", + "source_instant_snapshot_id": "source_instant_snapshot_id_value", "source_snapshot": "source_snapshot_value", "source_snapshot_encryption_key": {}, "source_snapshot_id": "source_snapshot_id_value", 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 4f88f53d0c2a..3b42ba1c9d04 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 @@ -1939,7 +1939,13 @@ def test_insert_rest(request_type): "creation_timestamp": "creation_timestamp_value", "description": "description_value", "id": 205, - "interfaces": [{"id": 205, "ip_address": "ip_address_value"}], + "interfaces": [ + { + "id": 205, + "ip_address": "ip_address_value", + "ipv6_address": "ipv6_address_value", + } + ], "kind": "kind_value", "label_fingerprint": "label_fingerprint_value", "labels": {}, @@ -2350,7 +2356,13 @@ def test_insert_unary_rest(request_type): "creation_timestamp": "creation_timestamp_value", "description": "description_value", "id": 205, - "interfaces": [{"id": 205, "ip_address": "ip_address_value"}], + "interfaces": [ + { + "id": 205, + "ip_address": "ip_address_value", + "ipv6_address": "ipv6_address_value", + } + ], "kind": "kind_value", "label_fingerprint": "label_fingerprint_value", "labels": {}, 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 936289629808..9c54eb09de48 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 @@ -6700,7 +6700,8 @@ def test_insert_rest(request_type): "id": 205, "instance_group": "instance_group_value", "instance_lifecycle_policy": { - "force_update_on_repair": "force_update_on_repair_value" + "default_action_on_failure": "default_action_on_failure_value", + "force_update_on_repair": "force_update_on_repair_value", }, "instance_template": "instance_template_value", "kind": "kind_value", @@ -7190,7 +7191,8 @@ def test_insert_unary_rest(request_type): "id": 205, "instance_group": "instance_group_value", "instance_lifecycle_policy": { - "force_update_on_repair": "force_update_on_repair_value" + "default_action_on_failure": "default_action_on_failure_value", + "force_update_on_repair": "force_update_on_repair_value", }, "instance_template": "instance_template_value", "kind": "kind_value", @@ -9184,7 +9186,8 @@ def test_patch_rest(request_type): "id": 205, "instance_group": "instance_group_value", "instance_lifecycle_policy": { - "force_update_on_repair": "force_update_on_repair_value" + "default_action_on_failure": "default_action_on_failure_value", + "force_update_on_repair": "force_update_on_repair_value", }, "instance_template": "instance_template_value", "kind": "kind_value", @@ -9693,7 +9696,8 @@ def test_patch_unary_rest(request_type): "id": 205, "instance_group": "instance_group_value", "instance_lifecycle_policy": { - "force_update_on_repair": "force_update_on_repair_value" + "default_action_on_failure": "default_action_on_failure_value", + "force_update_on_repair": "force_update_on_repair_value", }, "instance_template": "instance_template_value", "kind": "kind_value", 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 new file mode 100644 index 000000000000..fc2871c3f617 --- /dev/null +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instant_snapshots.py @@ -0,0 +1,5945 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import Iterable +import json +import math + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import extended_operation # type: ignore +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +from google.cloud.compute_v1.services.instant_snapshots import ( + InstantSnapshotsClient, + pagers, + transports, +) +from google.cloud.compute_v1.types import compute + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert InstantSnapshotsClient._get_default_mtls_endpoint(None) is None + assert ( + InstantSnapshotsClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + InstantSnapshotsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + InstantSnapshotsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + InstantSnapshotsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + InstantSnapshotsClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert InstantSnapshotsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert InstantSnapshotsClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert InstantSnapshotsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + InstantSnapshotsClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert InstantSnapshotsClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert InstantSnapshotsClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert InstantSnapshotsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + InstantSnapshotsClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert InstantSnapshotsClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert InstantSnapshotsClient._get_client_cert_source(None, False) is None + assert ( + InstantSnapshotsClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + InstantSnapshotsClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + InstantSnapshotsClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + InstantSnapshotsClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + InstantSnapshotsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(InstantSnapshotsClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = InstantSnapshotsClient._DEFAULT_UNIVERSE + default_endpoint = InstantSnapshotsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = InstantSnapshotsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + InstantSnapshotsClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + InstantSnapshotsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == InstantSnapshotsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + InstantSnapshotsClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + InstantSnapshotsClient._get_api_endpoint(None, None, default_universe, "always") + == InstantSnapshotsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + InstantSnapshotsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == InstantSnapshotsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + InstantSnapshotsClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + InstantSnapshotsClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + InstantSnapshotsClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + InstantSnapshotsClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + InstantSnapshotsClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + InstantSnapshotsClient._get_universe_domain(None, None) + == InstantSnapshotsClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + InstantSnapshotsClient._get_universe_domain("", None) + 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", + [ + (InstantSnapshotsClient, "rest"), + ], +) +def test_instant_snapshots_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.InstantSnapshotsRestTransport, "rest"), + ], +) +def test_instant_snapshots_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (InstantSnapshotsClient, "rest"), + ], +) +def test_instant_snapshots_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +def test_instant_snapshots_client_get_transport_class(): + transport = InstantSnapshotsClient.get_transport_class() + available_transports = [ + transports.InstantSnapshotsRestTransport, + ] + assert transport in available_transports + + transport = InstantSnapshotsClient.get_transport_class("rest") + assert transport == transports.InstantSnapshotsRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (InstantSnapshotsClient, transports.InstantSnapshotsRestTransport, "rest"), + ], +) +@mock.patch.object( + InstantSnapshotsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(InstantSnapshotsClient), +) +def test_instant_snapshots_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(InstantSnapshotsClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(InstantSnapshotsClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + InstantSnapshotsClient, + transports.InstantSnapshotsRestTransport, + "rest", + "true", + ), + ( + InstantSnapshotsClient, + transports.InstantSnapshotsRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + InstantSnapshotsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(InstantSnapshotsClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_instant_snapshots_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [InstantSnapshotsClient]) +@mock.patch.object( + InstantSnapshotsClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(InstantSnapshotsClient), +) +def test_instant_snapshots_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize("client_class", [InstantSnapshotsClient]) +@mock.patch.object( + InstantSnapshotsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(InstantSnapshotsClient), +) +def test_instant_snapshots_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = InstantSnapshotsClient._DEFAULT_UNIVERSE + default_endpoint = InstantSnapshotsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = InstantSnapshotsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (InstantSnapshotsClient, transports.InstantSnapshotsRestTransport, "rest"), + ], +) +def test_instant_snapshots_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + InstantSnapshotsClient, + transports.InstantSnapshotsRestTransport, + "rest", + None, + ), + ], +) +def test_instant_snapshots_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.AggregatedListInstantSnapshotsRequest, + dict, + ], +) +def test_aggregated_list_rest(request_type): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.InstantSnapshotAggregatedList( + id="id_value", + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + unreachables=["unreachables_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.InstantSnapshotAggregatedList.pb(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.aggregated_list(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.AggregatedListPager) + assert response.id == "id_value" + assert response.kind == "kind_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + assert response.unreachables == ["unreachables_value"] + + +def test_aggregated_list_rest_required_fields( + request_type=compute.AggregatedListInstantSnapshotsRequest, +): + transport_class = transports.InstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).aggregated_list._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).aggregated_list._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "include_all_scopes", + "max_results", + "order_by", + "page_token", + "return_partial_success", + "service_project_number", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.InstantSnapshotAggregatedList() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.InstantSnapshotAggregatedList.pb(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.aggregated_list(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_aggregated_list_rest_unset_required_fields(): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.aggregated_list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "includeAllScopes", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + "serviceProjectNumber", + ) + ) + & set(("project",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_aggregated_list_rest_interceptors(null_interceptor): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.InstantSnapshotsRestInterceptor(), + ) + client = InstantSnapshotsClient(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.InstantSnapshotsRestInterceptor, "post_aggregated_list" + ) as post, mock.patch.object( + transports.InstantSnapshotsRestInterceptor, "pre_aggregated_list" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.AggregatedListInstantSnapshotsRequest.pb( + compute.AggregatedListInstantSnapshotsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.InstantSnapshotAggregatedList.to_json( + compute.InstantSnapshotAggregatedList() + ) + + request = compute.AggregatedListInstantSnapshotsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.InstantSnapshotAggregatedList() + + client.aggregated_list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_aggregated_list_rest_bad_request( + transport: str = "rest", request_type=compute.AggregatedListInstantSnapshotsRequest +): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.aggregated_list(request) + + +def test_aggregated_list_rest_flattened(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.InstantSnapshotAggregatedList() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.InstantSnapshotAggregatedList.pb(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.aggregated_list(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/aggregated/instantSnapshots" + % client.transport._host, + args[1], + ) + + +def test_aggregated_list_rest_flattened_error(transport: str = "rest"): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.aggregated_list( + compute.AggregatedListInstantSnapshotsRequest(), + project="project_value", + ) + + +def test_aggregated_list_rest_pager(transport: str = "rest"): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + compute.InstantSnapshotAggregatedList( + items={ + "a": compute.InstantSnapshotsScopedList(), + "b": compute.InstantSnapshotsScopedList(), + "c": compute.InstantSnapshotsScopedList(), + }, + next_page_token="abc", + ), + compute.InstantSnapshotAggregatedList( + items={}, + next_page_token="def", + ), + compute.InstantSnapshotAggregatedList( + items={ + "g": compute.InstantSnapshotsScopedList(), + }, + next_page_token="ghi", + ), + compute.InstantSnapshotAggregatedList( + items={ + "h": compute.InstantSnapshotsScopedList(), + "i": compute.InstantSnapshotsScopedList(), + }, + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + compute.InstantSnapshotAggregatedList.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"project": "sample1"} + + pager = client.aggregated_list(request=sample_request) + + assert isinstance(pager.get("a"), compute.InstantSnapshotsScopedList) + assert pager.get("h") is None + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tuple) for i in results) + for result in results: + assert isinstance(result, tuple) + assert tuple(type(t) for t in result) == ( + str, + compute.InstantSnapshotsScopedList, + ) + + assert pager.get("a") is None + assert isinstance(pager.get("h"), compute.InstantSnapshotsScopedList) + + pages = list(client.aggregated_list(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + compute.DeleteInstantSnapshotRequest, + dict, + ], +) +def test_delete_rest(request_type): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "zone": "sample2", + "instant_snapshot": "sample3", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +def test_delete_rest_required_fields(request_type=compute.DeleteInstantSnapshotRequest): + transport_class = transports.InstantSnapshotsRestTransport + + request_init = {} + request_init["instant_snapshot"] = "" + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instantSnapshot"] = "instant_snapshot_value" + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "instantSnapshot" in jsonified_request + assert jsonified_request["instantSnapshot"] == "instant_snapshot_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_rest_unset_required_fields(): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "instantSnapshot", + "project", + "zone", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_rest_interceptors(null_interceptor): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.InstantSnapshotsRestInterceptor(), + ) + client = InstantSnapshotsClient(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.InstantSnapshotsRestInterceptor, "post_delete" + ) as post, mock.patch.object( + transports.InstantSnapshotsRestInterceptor, "pre_delete" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.DeleteInstantSnapshotRequest.pb( + compute.DeleteInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.DeleteInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.delete( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_rest_bad_request( + transport: str = "rest", request_type=compute.DeleteInstantSnapshotRequest +): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "zone": "sample2", + "instant_snapshot": "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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete(request) + + +def test_delete_rest_flattened(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "instant_snapshot": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + instant_snapshot="instant_snapshot_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/zones/{zone}/instantSnapshots/{instant_snapshot}" + % client.transport._host, + args[1], + ) + + +def test_delete_rest_flattened_error(transport: str = "rest"): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete( + compute.DeleteInstantSnapshotRequest(), + project="project_value", + zone="zone_value", + instant_snapshot="instant_snapshot_value", + ) + + +def test_delete_rest_error(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.DeleteInstantSnapshotRequest, + dict, + ], +) +def test_delete_unary_rest(request_type): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "zone": "sample2", + "instant_snapshot": "sample3", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_unary(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + + +def test_delete_unary_rest_required_fields( + request_type=compute.DeleteInstantSnapshotRequest, +): + transport_class = transports.InstantSnapshotsRestTransport + + request_init = {} + request_init["instant_snapshot"] = "" + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instantSnapshot"] = "instant_snapshot_value" + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "instantSnapshot" in jsonified_request + assert jsonified_request["instantSnapshot"] == "instant_snapshot_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_unary_rest_unset_required_fields(): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "instantSnapshot", + "project", + "zone", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_unary_rest_interceptors(null_interceptor): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.InstantSnapshotsRestInterceptor(), + ) + client = InstantSnapshotsClient(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.InstantSnapshotsRestInterceptor, "post_delete" + ) as post, mock.patch.object( + transports.InstantSnapshotsRestInterceptor, "pre_delete" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.DeleteInstantSnapshotRequest.pb( + compute.DeleteInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.DeleteInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.delete_unary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_unary_rest_bad_request( + transport: str = "rest", request_type=compute.DeleteInstantSnapshotRequest +): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "zone": "sample2", + "instant_snapshot": "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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_unary(request) + + +def test_delete_unary_rest_flattened(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "instant_snapshot": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + instant_snapshot="instant_snapshot_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/zones/{zone}/instantSnapshots/{instant_snapshot}" + % client.transport._host, + args[1], + ) + + +def test_delete_unary_rest_flattened_error(transport: str = "rest"): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_unary( + compute.DeleteInstantSnapshotRequest(), + project="project_value", + zone="zone_value", + instant_snapshot="instant_snapshot_value", + ) + + +def test_delete_unary_rest_error(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetInstantSnapshotRequest, + dict, + ], +) +def test_get_rest(request_type): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "zone": "sample2", + "instant_snapshot": "sample3", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.InstantSnapshot( + architecture="architecture_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + disk_size_gb=1261, + id=205, + kind="kind_value", + label_fingerprint="label_fingerprint_value", + name="name_value", + region="region_value", + satisfies_pzi=True, + satisfies_pzs=True, + self_link="self_link_value", + self_link_with_id="self_link_with_id_value", + source_disk="source_disk_value", + source_disk_id="source_disk_id_value", + status="status_value", + zone="zone_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 = compute.InstantSnapshot.pb(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(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.InstantSnapshot) + assert response.architecture == "architecture_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.disk_size_gb == 1261 + assert response.id == 205 + assert response.kind == "kind_value" + assert response.label_fingerprint == "label_fingerprint_value" + assert response.name == "name_value" + assert response.region == "region_value" + assert response.satisfies_pzi is True + assert response.satisfies_pzs is True + assert response.self_link == "self_link_value" + assert response.self_link_with_id == "self_link_with_id_value" + assert response.source_disk == "source_disk_value" + assert response.source_disk_id == "source_disk_id_value" + assert response.status == "status_value" + assert response.zone == "zone_value" + + +def test_get_rest_required_fields(request_type=compute.GetInstantSnapshotRequest): + transport_class = transports.InstantSnapshotsRestTransport + + request_init = {} + request_init["instant_snapshot"] = "" + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instantSnapshot"] = "instant_snapshot_value" + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "instantSnapshot" in jsonified_request + assert jsonified_request["instantSnapshot"] == "instant_snapshot_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.InstantSnapshot() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.InstantSnapshot.pb(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(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_rest_unset_required_fields(): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "instantSnapshot", + "project", + "zone", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.InstantSnapshotsRestInterceptor(), + ) + client = InstantSnapshotsClient(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.InstantSnapshotsRestInterceptor, "post_get" + ) as post, mock.patch.object( + transports.InstantSnapshotsRestInterceptor, "pre_get" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.GetInstantSnapshotRequest.pb( + compute.GetInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.InstantSnapshot.to_json( + compute.InstantSnapshot() + ) + + request = compute.GetInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.InstantSnapshot() + + client.get( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_rest_bad_request( + transport: str = "rest", request_type=compute.GetInstantSnapshotRequest +): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "zone": "sample2", + "instant_snapshot": "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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get(request) + + +def test_get_rest_flattened(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.InstantSnapshot() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "instant_snapshot": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + instant_snapshot="instant_snapshot_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.InstantSnapshot.pb(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(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/zones/{zone}/instantSnapshots/{instant_snapshot}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get( + compute.GetInstantSnapshotRequest(), + project="project_value", + zone="zone_value", + instant_snapshot="instant_snapshot_value", + ) + + +def test_get_rest_error(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetIamPolicyInstantSnapshotRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "resource": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy( + etag="etag_value", + iam_owned=True, + version=774, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Policy) + assert response.etag == "etag_value" + assert response.iam_owned is True + assert response.version == 774 + + +def test_get_iam_policy_rest_required_fields( + request_type=compute.GetIamPolicyInstantSnapshotRequest, +): + transport_class = transports.InstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["resource"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["resource"] = "resource_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_iam_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("options_requested_policy_version",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_iam_policy(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("optionsRequestedPolicyVersion",)) + & set( + ( + "project", + "resource", + "zone", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.InstantSnapshotsRestInterceptor(), + ) + client = InstantSnapshotsClient(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.InstantSnapshotsRestInterceptor, "post_get_iam_policy" + ) as post, mock.patch.object( + transports.InstantSnapshotsRestInterceptor, "pre_get_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.GetIamPolicyInstantSnapshotRequest.pb( + compute.GetIamPolicyInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Policy.to_json(compute.Policy()) + + request = compute.GetIamPolicyInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Policy() + + client.get_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request( + transport: str = "rest", request_type=compute.GetIamPolicyInstantSnapshotRequest +): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "resource": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "resource": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + resource="resource_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/zones/{zone}/instantSnapshots/{resource}/getIamPolicy" + % client.transport._host, + args[1], + ) + + +def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_iam_policy( + compute.GetIamPolicyInstantSnapshotRequest(), + project="project_value", + zone="zone_value", + resource="resource_value", + ) + + +def test_get_iam_policy_rest_error(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.InsertInstantSnapshotRequest, + dict, + ], +) +def test_insert_rest(request_type): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2"} + request_init["instant_snapshot_resource"] = { + "architecture": "architecture_value", + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "disk_size_gb": 1261, + "id": 205, + "kind": "kind_value", + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + "name": "name_value", + "region": "region_value", + "resource_status": {"storage_size_bytes": 1941}, + "satisfies_pzi": True, + "satisfies_pzs": True, + "self_link": "self_link_value", + "self_link_with_id": "self_link_with_id_value", + "source_disk": "source_disk_value", + "source_disk_id": "source_disk_id_value", + "status": "status_value", + "zone": "zone_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.InsertInstantSnapshotRequest.meta.fields[ + "instant_snapshot_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "instant_snapshot_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["instant_snapshot_resource"][field]) + ): + del request_init["instant_snapshot_resource"][field][i][subfield] + else: + del request_init["instant_snapshot_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.insert(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +def test_insert_rest_required_fields(request_type=compute.InsertInstantSnapshotRequest): + transport_class = transports.InstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.insert(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_insert_rest_unset_required_fields(): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "instantSnapshotResource", + "project", + "zone", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_rest_interceptors(null_interceptor): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.InstantSnapshotsRestInterceptor(), + ) + client = InstantSnapshotsClient(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.InstantSnapshotsRestInterceptor, "post_insert" + ) as post, mock.patch.object( + transports.InstantSnapshotsRestInterceptor, "pre_insert" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.InsertInstantSnapshotRequest.pb( + compute.InsertInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.InsertInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.insert( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_insert_rest_bad_request( + transport: str = "rest", request_type=compute.InsertInstantSnapshotRequest +): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.insert(request) + + +def test_insert_rest_flattened(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "zone": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + instant_snapshot_resource=compute.InstantSnapshot( + architecture="architecture_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.insert(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/zones/{zone}/instantSnapshots" + % client.transport._host, + args[1], + ) + + +def test_insert_rest_flattened_error(transport: str = "rest"): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.insert( + compute.InsertInstantSnapshotRequest(), + project="project_value", + zone="zone_value", + instant_snapshot_resource=compute.InstantSnapshot( + architecture="architecture_value" + ), + ) + + +def test_insert_rest_error(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.InsertInstantSnapshotRequest, + dict, + ], +) +def test_insert_unary_rest(request_type): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2"} + request_init["instant_snapshot_resource"] = { + "architecture": "architecture_value", + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "disk_size_gb": 1261, + "id": 205, + "kind": "kind_value", + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + "name": "name_value", + "region": "region_value", + "resource_status": {"storage_size_bytes": 1941}, + "satisfies_pzi": True, + "satisfies_pzs": True, + "self_link": "self_link_value", + "self_link_with_id": "self_link_with_id_value", + "source_disk": "source_disk_value", + "source_disk_id": "source_disk_id_value", + "status": "status_value", + "zone": "zone_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.InsertInstantSnapshotRequest.meta.fields[ + "instant_snapshot_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "instant_snapshot_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["instant_snapshot_resource"][field]) + ): + del request_init["instant_snapshot_resource"][field][i][subfield] + else: + del request_init["instant_snapshot_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.insert_unary(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + + +def test_insert_unary_rest_required_fields( + request_type=compute.InsertInstantSnapshotRequest, +): + transport_class = transports.InstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.insert_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_insert_unary_rest_unset_required_fields(): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "instantSnapshotResource", + "project", + "zone", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_unary_rest_interceptors(null_interceptor): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.InstantSnapshotsRestInterceptor(), + ) + client = InstantSnapshotsClient(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.InstantSnapshotsRestInterceptor, "post_insert" + ) as post, mock.patch.object( + transports.InstantSnapshotsRestInterceptor, "pre_insert" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.InsertInstantSnapshotRequest.pb( + compute.InsertInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.InsertInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.insert_unary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_insert_unary_rest_bad_request( + transport: str = "rest", request_type=compute.InsertInstantSnapshotRequest +): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.insert_unary(request) + + +def test_insert_unary_rest_flattened(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "zone": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + instant_snapshot_resource=compute.InstantSnapshot( + architecture="architecture_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.insert_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/zones/{zone}/instantSnapshots" + % client.transport._host, + args[1], + ) + + +def test_insert_unary_rest_flattened_error(transport: str = "rest"): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.insert_unary( + compute.InsertInstantSnapshotRequest(), + project="project_value", + zone="zone_value", + instant_snapshot_resource=compute.InstantSnapshot( + architecture="architecture_value" + ), + ) + + +def test_insert_unary_rest_error(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ListInstantSnapshotsRequest, + dict, + ], +) +def test_list_rest(request_type): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.InstantSnapshotList( + id="id_value", + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.InstantSnapshotList.pb(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(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPager) + assert response.id == "id_value" + assert response.kind == "kind_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + + +def test_list_rest_required_fields(request_type=compute.ListInstantSnapshotsRequest): + transport_class = transports.InstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "max_results", + "order_by", + "page_token", + "return_partial_success", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.InstantSnapshotList() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.InstantSnapshotList.pb(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(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_rest_unset_required_fields(): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set( + ( + "project", + "zone", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rest_interceptors(null_interceptor): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.InstantSnapshotsRestInterceptor(), + ) + client = InstantSnapshotsClient(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.InstantSnapshotsRestInterceptor, "post_list" + ) as post, mock.patch.object( + transports.InstantSnapshotsRestInterceptor, "pre_list" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.ListInstantSnapshotsRequest.pb( + compute.ListInstantSnapshotsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.InstantSnapshotList.to_json( + compute.InstantSnapshotList() + ) + + request = compute.ListInstantSnapshotsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.InstantSnapshotList() + + client.list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_rest_bad_request( + transport: str = "rest", request_type=compute.ListInstantSnapshotsRequest +): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list(request) + + +def test_list_rest_flattened(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.InstantSnapshotList() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "zone": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.InstantSnapshotList.pb(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(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/zones/{zone}/instantSnapshots" + % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list( + compute.ListInstantSnapshotsRequest(), + project="project_value", + zone="zone_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + compute.InstantSnapshotList( + items=[ + compute.InstantSnapshot(), + compute.InstantSnapshot(), + compute.InstantSnapshot(), + ], + next_page_token="abc", + ), + compute.InstantSnapshotList( + items=[], + next_page_token="def", + ), + compute.InstantSnapshotList( + items=[ + compute.InstantSnapshot(), + ], + next_page_token="ghi", + ), + compute.InstantSnapshotList( + items=[ + compute.InstantSnapshot(), + compute.InstantSnapshot(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.InstantSnapshotList.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"project": "sample1", "zone": "sample2"} + + pager = client.list(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.InstantSnapshot) for i in results) + + pages = list(client.list(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + compute.SetIamPolicyInstantSnapshotRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "resource": "sample3"} + request_init["zone_set_policy_request_resource"] = { + "bindings": [ + { + "binding_id": "binding_id_value", + "condition": { + "description": "description_value", + "expression": "expression_value", + "location": "location_value", + "title": "title_value", + }, + "members": ["members_value1", "members_value2"], + "role": "role_value", + } + ], + "etag": "etag_value", + "policy": { + "audit_configs": [ + { + "audit_log_configs": [ + { + "exempted_members": [ + "exempted_members_value1", + "exempted_members_value2", + ], + "ignore_child_exemptions": True, + "log_type": "log_type_value", + } + ], + "exempted_members": [ + "exempted_members_value1", + "exempted_members_value2", + ], + "service": "service_value", + } + ], + "bindings": {}, + "etag": "etag_value", + "iam_owned": True, + "rules": [ + { + "action": "action_value", + "conditions": [ + { + "iam": "iam_value", + "op": "op_value", + "svc": "svc_value", + "sys": "sys_value", + "values": ["values_value1", "values_value2"], + } + ], + "description": "description_value", + "ins": ["ins_value1", "ins_value2"], + "log_configs": [ + { + "cloud_audit": { + "authorization_logging_options": { + "permission_type": "permission_type_value" + }, + "log_name": "log_name_value", + }, + "counter": { + "custom_fields": [ + {"name": "name_value", "value": "value_value"} + ], + "field": "field_value", + "metric": "metric_value", + }, + "data_access": {"log_mode": "log_mode_value"}, + } + ], + "not_ins": ["not_ins_value1", "not_ins_value2"], + "permissions": ["permissions_value1", "permissions_value2"], + } + ], + "version": 774, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.SetIamPolicyInstantSnapshotRequest.meta.fields[ + "zone_set_policy_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "zone_set_policy_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["zone_set_policy_request_resource"][field]) + ): + del request_init["zone_set_policy_request_resource"][field][i][ + subfield + ] + else: + del request_init["zone_set_policy_request_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy( + etag="etag_value", + iam_owned=True, + version=774, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Policy) + assert response.etag == "etag_value" + assert response.iam_owned is True + assert response.version == 774 + + +def test_set_iam_policy_rest_required_fields( + request_type=compute.SetIamPolicyInstantSnapshotRequest, +): + transport_class = transports.InstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["resource"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["resource"] = "resource_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.set_iam_policy(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "project", + "resource", + "zone", + "zoneSetPolicyRequestResource", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.InstantSnapshotsRestInterceptor(), + ) + client = InstantSnapshotsClient(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.InstantSnapshotsRestInterceptor, "post_set_iam_policy" + ) as post, mock.patch.object( + transports.InstantSnapshotsRestInterceptor, "pre_set_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.SetIamPolicyInstantSnapshotRequest.pb( + compute.SetIamPolicyInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Policy.to_json(compute.Policy()) + + request = compute.SetIamPolicyInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Policy() + + client.set_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request( + transport: str = "rest", request_type=compute.SetIamPolicyInstantSnapshotRequest +): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "resource": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "resource": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + resource="resource_value", + zone_set_policy_request_resource=compute.ZoneSetPolicyRequest( + bindings=[compute.Binding(binding_id="binding_id_value")] + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.set_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/zones/{zone}/instantSnapshots/{resource}/setIamPolicy" + % client.transport._host, + args[1], + ) + + +def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + compute.SetIamPolicyInstantSnapshotRequest(), + project="project_value", + zone="zone_value", + resource="resource_value", + zone_set_policy_request_resource=compute.ZoneSetPolicyRequest( + bindings=[compute.Binding(binding_id="binding_id_value")] + ), + ) + + +def test_set_iam_policy_rest_error(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.SetLabelsInstantSnapshotRequest, + dict, + ], +) +def test_set_labels_rest(request_type): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "resource": "sample3"} + request_init["zone_set_labels_request_resource"] = { + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.SetLabelsInstantSnapshotRequest.meta.fields[ + "zone_set_labels_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "zone_set_labels_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["zone_set_labels_request_resource"][field]) + ): + del request_init["zone_set_labels_request_resource"][field][i][ + subfield + ] + else: + del request_init["zone_set_labels_request_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_labels(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +def test_set_labels_rest_required_fields( + request_type=compute.SetLabelsInstantSnapshotRequest, +): + transport_class = transports.InstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["resource"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_labels._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["resource"] = "resource_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_labels._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.set_labels(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_labels_rest_unset_required_fields(): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_labels._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "resource", + "zone", + "zoneSetLabelsRequestResource", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_labels_rest_interceptors(null_interceptor): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.InstantSnapshotsRestInterceptor(), + ) + client = InstantSnapshotsClient(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.InstantSnapshotsRestInterceptor, "post_set_labels" + ) as post, mock.patch.object( + transports.InstantSnapshotsRestInterceptor, "pre_set_labels" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.SetLabelsInstantSnapshotRequest.pb( + compute.SetLabelsInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.SetLabelsInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.set_labels( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_labels_rest_bad_request( + transport: str = "rest", request_type=compute.SetLabelsInstantSnapshotRequest +): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "resource": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_labels(request) + + +def test_set_labels_rest_flattened(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "resource": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + resource="resource_value", + zone_set_labels_request_resource=compute.ZoneSetLabelsRequest( + label_fingerprint="label_fingerprint_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.set_labels(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/zones/{zone}/instantSnapshots/{resource}/setLabels" + % client.transport._host, + args[1], + ) + + +def test_set_labels_rest_flattened_error(transport: str = "rest"): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_labels( + compute.SetLabelsInstantSnapshotRequest(), + project="project_value", + zone="zone_value", + resource="resource_value", + zone_set_labels_request_resource=compute.ZoneSetLabelsRequest( + label_fingerprint="label_fingerprint_value" + ), + ) + + +def test_set_labels_rest_error(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.SetLabelsInstantSnapshotRequest, + dict, + ], +) +def test_set_labels_unary_rest(request_type): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "resource": "sample3"} + request_init["zone_set_labels_request_resource"] = { + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.SetLabelsInstantSnapshotRequest.meta.fields[ + "zone_set_labels_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "zone_set_labels_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["zone_set_labels_request_resource"][field]) + ): + del request_init["zone_set_labels_request_resource"][field][i][ + subfield + ] + else: + del request_init["zone_set_labels_request_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_labels_unary(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + + +def test_set_labels_unary_rest_required_fields( + request_type=compute.SetLabelsInstantSnapshotRequest, +): + transport_class = transports.InstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["resource"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_labels._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["resource"] = "resource_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_labels._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.set_labels_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_labels_unary_rest_unset_required_fields(): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_labels._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "resource", + "zone", + "zoneSetLabelsRequestResource", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_labels_unary_rest_interceptors(null_interceptor): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.InstantSnapshotsRestInterceptor(), + ) + client = InstantSnapshotsClient(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.InstantSnapshotsRestInterceptor, "post_set_labels" + ) as post, mock.patch.object( + transports.InstantSnapshotsRestInterceptor, "pre_set_labels" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.SetLabelsInstantSnapshotRequest.pb( + compute.SetLabelsInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.SetLabelsInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.set_labels_unary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_labels_unary_rest_bad_request( + transport: str = "rest", request_type=compute.SetLabelsInstantSnapshotRequest +): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "resource": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_labels_unary(request) + + +def test_set_labels_unary_rest_flattened(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "resource": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + resource="resource_value", + zone_set_labels_request_resource=compute.ZoneSetLabelsRequest( + label_fingerprint="label_fingerprint_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.set_labels_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/zones/{zone}/instantSnapshots/{resource}/setLabels" + % client.transport._host, + args[1], + ) + + +def test_set_labels_unary_rest_flattened_error(transport: str = "rest"): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_labels_unary( + compute.SetLabelsInstantSnapshotRequest(), + project="project_value", + zone="zone_value", + resource="resource_value", + zone_set_labels_request_resource=compute.ZoneSetLabelsRequest( + label_fingerprint="label_fingerprint_value" + ), + ) + + +def test_set_labels_unary_rest_error(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.TestIamPermissionsInstantSnapshotRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "resource": "sample3"} + request_init["test_permissions_request_resource"] = { + "permissions": ["permissions_value1", "permissions_value2"] + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.TestIamPermissionsInstantSnapshotRequest.meta.fields[ + "test_permissions_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "test_permissions_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["test_permissions_request_resource"][field]) + ): + del request_init["test_permissions_request_resource"][field][i][ + subfield + ] + else: + del request_init["test_permissions_request_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.TestPermissionsResponse( + permissions=["permissions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.TestPermissionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.TestPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_rest_required_fields( + request_type=compute.TestIamPermissionsInstantSnapshotRequest, +): + transport_class = transports.InstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["resource"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["resource"] = "resource_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.TestPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.TestPermissionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.test_iam_permissions(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "project", + "resource", + "testPermissionsRequestResource", + "zone", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.InstantSnapshotsRestInterceptor(), + ) + client = InstantSnapshotsClient(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.InstantSnapshotsRestInterceptor, "post_test_iam_permissions" + ) as post, mock.patch.object( + transports.InstantSnapshotsRestInterceptor, "pre_test_iam_permissions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.TestIamPermissionsInstantSnapshotRequest.pb( + compute.TestIamPermissionsInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.TestPermissionsResponse.to_json( + compute.TestPermissionsResponse() + ) + + request = compute.TestIamPermissionsInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.TestPermissionsResponse() + + client.test_iam_permissions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request( + transport: str = "rest", + request_type=compute.TestIamPermissionsInstantSnapshotRequest, +): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "resource": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.TestPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "resource": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + resource="resource_value", + test_permissions_request_resource=compute.TestPermissionsRequest( + permissions=["permissions_value"] + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.TestPermissionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.test_iam_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/zones/{zone}/instantSnapshots/{resource}/testIamPermissions" + % client.transport._host, + args[1], + ) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + compute.TestIamPermissionsInstantSnapshotRequest(), + project="project_value", + zone="zone_value", + resource="resource_value", + test_permissions_request_resource=compute.TestPermissionsRequest( + permissions=["permissions_value"] + ), + ) + + +def test_test_iam_permissions_rest_error(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = InstantSnapshotsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = InstantSnapshotsClient( + 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 = InstantSnapshotsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = InstantSnapshotsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.InstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = InstantSnapshotsClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.InstantSnapshotsRestTransport, + ], +) +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() + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_transport_kind(transport_name): + transport = InstantSnapshotsClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_instant_snapshots_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.InstantSnapshotsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_instant_snapshots_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1.services.instant_snapshots.transports.InstantSnapshotsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.InstantSnapshotsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "aggregated_list", + "delete", + "get", + "get_iam_policy", + "insert", + "list", + "set_iam_policy", + "set_labels", + "test_iam_permissions", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_instant_snapshots_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.instant_snapshots.transports.InstantSnapshotsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.InstantSnapshotsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_instant_snapshots_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.compute_v1.services.instant_snapshots.transports.InstantSnapshotsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.InstantSnapshotsTransport() + adc.assert_called_once() + + +def test_instant_snapshots_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + InstantSnapshotsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_instant_snapshots_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.InstantSnapshotsRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_instant_snapshots_host_no_port(transport_name): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_instant_snapshots_host_with_port(transport_name): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_instant_snapshots_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = InstantSnapshotsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = InstantSnapshotsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.aggregated_list._session + session2 = client2.transport.aggregated_list._session + assert session1 != session2 + session1 = client1.transport.delete._session + session2 = client2.transport.delete._session + assert session1 != session2 + session1 = client1.transport.get._session + session2 = client2.transport.get._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.insert._session + session2 = client2.transport.insert._session + assert session1 != session2 + session1 = client1.transport.list._session + session2 = client2.transport.list._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.set_labels._session + session2 = client2.transport.set_labels._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = InstantSnapshotsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = InstantSnapshotsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = InstantSnapshotsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = InstantSnapshotsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = InstantSnapshotsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = InstantSnapshotsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = InstantSnapshotsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = InstantSnapshotsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = InstantSnapshotsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = InstantSnapshotsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = InstantSnapshotsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = InstantSnapshotsClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = InstantSnapshotsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = InstantSnapshotsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = InstantSnapshotsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.InstantSnapshotsTransport, "_prep_wrapped_messages" + ) as prep: + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.InstantSnapshotsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = InstantSnapshotsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close(): + transports = { + "rest": "_session", + } + + for transport, close_name in transports.items(): + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + ] + for transport in transports: + client = InstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (InstantSnapshotsClient, transports.InstantSnapshotsRestTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_projects.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_projects.py index a92f5c6d1668..4915848f7f05 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 @@ -3706,6 +3706,7 @@ def test_get_rest(request_type): with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Project( + cloud_armor_tier="cloud_armor_tier_value", creation_timestamp="creation_timestamp_value", default_network_tier="default_network_tier_value", default_service_account="default_service_account_value", @@ -3732,6 +3733,7 @@ def test_get_rest(request_type): # Establish that the response is the type that we expect. assert isinstance(response, compute.Project) + assert response.cloud_armor_tier == "cloud_armor_tier_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.default_network_tier == "default_network_tier_value" assert response.default_service_account == "default_service_account_value" @@ -3983,6 +3985,7 @@ def test_get_xpn_host_rest(request_type): with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Project( + cloud_armor_tier="cloud_armor_tier_value", creation_timestamp="creation_timestamp_value", default_network_tier="default_network_tier_value", default_service_account="default_service_account_value", @@ -4009,6 +4012,7 @@ def test_get_xpn_host_rest(request_type): # Establish that the response is the type that we expect. assert isinstance(response, compute.Project) + assert response.cloud_armor_tier == "cloud_armor_tier_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.default_network_tier == "default_network_tier_value" assert response.default_service_account == "default_service_account_value" @@ -6574,6 +6578,798 @@ def test_move_instance_unary_rest_error(): ) +@pytest.mark.parametrize( + "request_type", + [ + compute.SetCloudArmorTierProjectRequest, + dict, + ], +) +def test_set_cloud_armor_tier_rest(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request_init["projects_set_cloud_armor_tier_request_resource"] = { + "cloud_armor_tier": "cloud_armor_tier_value" + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.SetCloudArmorTierProjectRequest.meta.fields[ + "projects_set_cloud_armor_tier_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "projects_set_cloud_armor_tier_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, + len( + request_init["projects_set_cloud_armor_tier_request_resource"][ + field + ] + ), + ): + del request_init["projects_set_cloud_armor_tier_request_resource"][ + field + ][i][subfield] + else: + del request_init["projects_set_cloud_armor_tier_request_resource"][ + field + ][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_cloud_armor_tier(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +def test_set_cloud_armor_tier_rest_required_fields( + request_type=compute.SetCloudArmorTierProjectRequest, +): + transport_class = transports.ProjectsRestTransport + + request_init = {} + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_cloud_armor_tier._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_cloud_armor_tier._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.set_cloud_armor_tier(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_cloud_armor_tier_rest_unset_required_fields(): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_cloud_armor_tier._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "projectsSetCloudArmorTierRequestResource", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_cloud_armor_tier_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(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.ProjectsRestInterceptor, "post_set_cloud_armor_tier" + ) as post, mock.patch.object( + transports.ProjectsRestInterceptor, "pre_set_cloud_armor_tier" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.SetCloudArmorTierProjectRequest.pb( + compute.SetCloudArmorTierProjectRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.SetCloudArmorTierProjectRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.set_cloud_armor_tier( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_cloud_armor_tier_rest_bad_request( + transport: str = "rest", request_type=compute.SetCloudArmorTierProjectRequest +): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_cloud_armor_tier(request) + + +def test_set_cloud_armor_tier_rest_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + projects_set_cloud_armor_tier_request_resource=compute.ProjectsSetCloudArmorTierRequest( + cloud_armor_tier="cloud_armor_tier_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.set_cloud_armor_tier(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/setCloudArmorTier" + % client.transport._host, + args[1], + ) + + +def test_set_cloud_armor_tier_rest_flattened_error(transport: str = "rest"): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_cloud_armor_tier( + compute.SetCloudArmorTierProjectRequest(), + project="project_value", + projects_set_cloud_armor_tier_request_resource=compute.ProjectsSetCloudArmorTierRequest( + cloud_armor_tier="cloud_armor_tier_value" + ), + ) + + +def test_set_cloud_armor_tier_rest_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.SetCloudArmorTierProjectRequest, + dict, + ], +) +def test_set_cloud_armor_tier_unary_rest(request_type): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request_init["projects_set_cloud_armor_tier_request_resource"] = { + "cloud_armor_tier": "cloud_armor_tier_value" + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.SetCloudArmorTierProjectRequest.meta.fields[ + "projects_set_cloud_armor_tier_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "projects_set_cloud_armor_tier_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, + len( + request_init["projects_set_cloud_armor_tier_request_resource"][ + field + ] + ), + ): + del request_init["projects_set_cloud_armor_tier_request_resource"][ + field + ][i][subfield] + else: + del request_init["projects_set_cloud_armor_tier_request_resource"][ + field + ][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_cloud_armor_tier_unary(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + + +def test_set_cloud_armor_tier_unary_rest_required_fields( + request_type=compute.SetCloudArmorTierProjectRequest, +): + transport_class = transports.ProjectsRestTransport + + request_init = {} + request_init["project"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_cloud_armor_tier._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_cloud_armor_tier._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.set_cloud_armor_tier_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_cloud_armor_tier_unary_rest_unset_required_fields(): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_cloud_armor_tier._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "projectsSetCloudArmorTierRequestResource", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_cloud_armor_tier_unary_rest_interceptors(null_interceptor): + transport = transports.ProjectsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProjectsRestInterceptor(), + ) + client = ProjectsClient(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.ProjectsRestInterceptor, "post_set_cloud_armor_tier" + ) as post, mock.patch.object( + transports.ProjectsRestInterceptor, "pre_set_cloud_armor_tier" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.SetCloudArmorTierProjectRequest.pb( + compute.SetCloudArmorTierProjectRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.SetCloudArmorTierProjectRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.set_cloud_armor_tier_unary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_cloud_armor_tier_unary_rest_bad_request( + transport: str = "rest", request_type=compute.SetCloudArmorTierProjectRequest +): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_cloud_armor_tier_unary(request) + + +def test_set_cloud_armor_tier_unary_rest_flattened(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + projects_set_cloud_armor_tier_request_resource=compute.ProjectsSetCloudArmorTierRequest( + cloud_armor_tier="cloud_armor_tier_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.set_cloud_armor_tier_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/setCloudArmorTier" + % client.transport._host, + args[1], + ) + + +def test_set_cloud_armor_tier_unary_rest_flattened_error(transport: str = "rest"): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_cloud_armor_tier_unary( + compute.SetCloudArmorTierProjectRequest(), + project="project_value", + projects_set_cloud_armor_tier_request_resource=compute.ProjectsSetCloudArmorTierRequest( + cloud_armor_tier="cloud_armor_tier_value" + ), + ) + + +def test_set_cloud_armor_tier_unary_rest_error(): + client = ProjectsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + @pytest.mark.parametrize( "request_type", [ @@ -9032,6 +9828,7 @@ def test_projects_base_transport(): "list_xpn_hosts", "move_disk", "move_instance", + "set_cloud_armor_tier", "set_common_instance_metadata", "set_default_network_tier", "set_usage_export_bucket", @@ -9202,6 +9999,9 @@ def test_projects_client_transport_session_collision(transport_name): session1 = client1.transport.move_instance._session session2 = client2.transport.move_instance._session assert session1 != session2 + session1 = client1.transport.set_cloud_armor_tier._session + session2 = client2.transport.set_cloud_armor_tier._session + assert session1 != session2 session1 = client1.transport.set_common_instance_metadata._session session2 = client2.transport.set_common_instance_metadata._session assert session1 != session2 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 af6f31916c6c..92e84727bac2 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 @@ -1715,6 +1715,7 @@ def test_get_rest(request_type): security_policy="security_policy_value", self_link="self_link_value", service_bindings=["service_bindings_value"], + service_lb_policy="service_lb_policy_value", session_affinity="session_affinity_value", timeout_sec=1185, ) @@ -1755,6 +1756,7 @@ def test_get_rest(request_type): assert response.security_policy == "security_policy_value" assert response.self_link == "self_link_value" assert response.service_bindings == ["service_bindings_value"] + assert response.service_lb_policy == "service_lb_policy_value" assert response.session_affinity == "session_affinity_value" assert response.timeout_sec == 1185 @@ -2725,6 +2727,7 @@ def test_insert_rest(request_type): "max_rate_per_endpoint": 0.22310000000000002, "max_rate_per_instance": 0.22190000000000001, "max_utilization": 0.1633, + "preference": "preference_value", } ], "cdn_policy": { @@ -2866,6 +2869,7 @@ def test_insert_rest(request_type): }, "self_link": "self_link_value", "service_bindings": ["service_bindings_value1", "service_bindings_value2"], + "service_lb_policy": "service_lb_policy_value", "session_affinity": "session_affinity_value", "subsetting": {"policy": "policy_value"}, "timeout_sec": 1185, @@ -3289,6 +3293,7 @@ def test_insert_unary_rest(request_type): "max_rate_per_endpoint": 0.22310000000000002, "max_rate_per_instance": 0.22190000000000001, "max_utilization": 0.1633, + "preference": "preference_value", } ], "cdn_policy": { @@ -3430,6 +3435,7 @@ def test_insert_unary_rest(request_type): }, "self_link": "self_link_value", "service_bindings": ["service_bindings_value1", "service_bindings_value2"], + "service_lb_policy": "service_lb_policy_value", "session_affinity": "session_affinity_value", "subsetting": {"policy": "policy_value"}, "timeout_sec": 1185, @@ -4555,6 +4561,7 @@ def test_patch_rest(request_type): "max_rate_per_endpoint": 0.22310000000000002, "max_rate_per_instance": 0.22190000000000001, "max_utilization": 0.1633, + "preference": "preference_value", } ], "cdn_policy": { @@ -4696,6 +4703,7 @@ def test_patch_rest(request_type): }, "self_link": "self_link_value", "service_bindings": ["service_bindings_value1", "service_bindings_value2"], + "service_lb_policy": "service_lb_policy_value", "session_affinity": "session_affinity_value", "subsetting": {"policy": "policy_value"}, "timeout_sec": 1185, @@ -5138,6 +5146,7 @@ def test_patch_unary_rest(request_type): "max_rate_per_endpoint": 0.22310000000000002, "max_rate_per_instance": 0.22190000000000001, "max_utilization": 0.1633, + "preference": "preference_value", } ], "cdn_policy": { @@ -5279,6 +5288,7 @@ def test_patch_unary_rest(request_type): }, "self_link": "self_link_value", "service_bindings": ["service_bindings_value1", "service_bindings_value2"], + "service_lb_policy": "service_lb_policy_value", "session_affinity": "session_affinity_value", "subsetting": {"policy": "policy_value"}, "timeout_sec": 1185, @@ -7369,6 +7379,7 @@ def test_update_rest(request_type): "max_rate_per_endpoint": 0.22310000000000002, "max_rate_per_instance": 0.22190000000000001, "max_utilization": 0.1633, + "preference": "preference_value", } ], "cdn_policy": { @@ -7510,6 +7521,7 @@ def test_update_rest(request_type): }, "self_link": "self_link_value", "service_bindings": ["service_bindings_value1", "service_bindings_value2"], + "service_lb_policy": "service_lb_policy_value", "session_affinity": "session_affinity_value", "subsetting": {"policy": "policy_value"}, "timeout_sec": 1185, @@ -7952,6 +7964,7 @@ def test_update_unary_rest(request_type): "max_rate_per_endpoint": 0.22310000000000002, "max_rate_per_instance": 0.22190000000000001, "max_utilization": 0.1633, + "preference": "preference_value", } ], "cdn_policy": { @@ -8093,6 +8106,7 @@ def test_update_unary_rest(request_type): }, "self_link": "self_link_value", "service_bindings": ["service_bindings_value1", "service_bindings_value2"], + "service_lb_policy": "service_lb_policy_value", "session_affinity": "session_affinity_value", "subsetting": {"policy": "policy_value"}, "timeout_sec": 1185, 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 5b07ee05d466..186f626bb698 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 @@ -2605,6 +2605,9 @@ def test_create_snapshot_rest(request_type): "source_disk_encryption_key": {}, "source_disk_for_recovery_checkpoint": "source_disk_for_recovery_checkpoint_value", "source_disk_id": "source_disk_id_value", + "source_instant_snapshot": "source_instant_snapshot_value", + "source_instant_snapshot_encryption_key": {}, + "source_instant_snapshot_id": "source_instant_snapshot_id_value", "source_snapshot_schedule_policy": "source_snapshot_schedule_policy_value", "source_snapshot_schedule_policy_id": "source_snapshot_schedule_policy_id_value", "status": "status_value", @@ -3049,6 +3052,9 @@ def test_create_snapshot_unary_rest(request_type): "source_disk_encryption_key": {}, "source_disk_for_recovery_checkpoint": "source_disk_for_recovery_checkpoint_value", "source_disk_id": "source_disk_id_value", + "source_instant_snapshot": "source_instant_snapshot_value", + "source_instant_snapshot_encryption_key": {}, + "source_instant_snapshot_id": "source_instant_snapshot_id_value", "source_snapshot_schedule_policy": "source_snapshot_schedule_policy_value", "source_snapshot_schedule_policy_id": "source_snapshot_schedule_policy_id_value", "status": "status_value", @@ -4109,6 +4115,8 @@ def test_get_rest(request_type): source_disk_id="source_disk_id_value", source_image="source_image_value", source_image_id="source_image_id_value", + source_instant_snapshot="source_instant_snapshot_value", + source_instant_snapshot_id="source_instant_snapshot_id_value", source_snapshot="source_snapshot_value", source_snapshot_id="source_snapshot_id_value", source_storage_object="source_storage_object_value", @@ -4167,6 +4175,8 @@ def test_get_rest(request_type): assert response.source_disk_id == "source_disk_id_value" assert response.source_image == "source_image_value" assert response.source_image_id == "source_image_id_value" + assert response.source_instant_snapshot == "source_instant_snapshot_value" + assert response.source_instant_snapshot_id == "source_instant_snapshot_id_value" assert response.source_snapshot == "source_snapshot_value" assert response.source_snapshot_id == "source_snapshot_id_value" assert response.source_storage_object == "source_storage_object_value" @@ -4782,6 +4792,8 @@ def test_insert_rest(request_type): "source_image": "source_image_value", "source_image_encryption_key": {}, "source_image_id": "source_image_id_value", + "source_instant_snapshot": "source_instant_snapshot_value", + "source_instant_snapshot_id": "source_instant_snapshot_id_value", "source_snapshot": "source_snapshot_value", "source_snapshot_encryption_key": {}, "source_snapshot_id": "source_snapshot_id_value", @@ -5246,6 +5258,8 @@ def test_insert_unary_rest(request_type): "source_image": "source_image_value", "source_image_encryption_key": {}, "source_image_id": "source_image_id_value", + "source_instant_snapshot": "source_instant_snapshot_value", + "source_instant_snapshot_id": "source_instant_snapshot_id_value", "source_snapshot": "source_snapshot_value", "source_snapshot_encryption_key": {}, "source_snapshot_id": "source_snapshot_id_value", @@ -11606,6 +11620,8 @@ def test_update_rest(request_type): "source_image": "source_image_value", "source_image_encryption_key": {}, "source_image_id": "source_image_id_value", + "source_instant_snapshot": "source_instant_snapshot_value", + "source_instant_snapshot_id": "source_instant_snapshot_id_value", "source_snapshot": "source_snapshot_value", "source_snapshot_encryption_key": {}, "source_snapshot_id": "source_snapshot_id_value", @@ -12079,6 +12095,8 @@ def test_update_unary_rest(request_type): "source_image": "source_image_value", "source_image_encryption_key": {}, "source_image_id": "source_image_id_value", + "source_instant_snapshot": "source_instant_snapshot_value", + "source_instant_snapshot_id": "source_instant_snapshot_id_value", "source_snapshot": "source_snapshot_value", "source_snapshot_encryption_key": {}, "source_snapshot_id": "source_snapshot_id_value", 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 7a8225aa9fb9..e09b3f945346 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 @@ -6362,7 +6362,8 @@ def test_insert_rest(request_type): "id": 205, "instance_group": "instance_group_value", "instance_lifecycle_policy": { - "force_update_on_repair": "force_update_on_repair_value" + "default_action_on_failure": "default_action_on_failure_value", + "force_update_on_repair": "force_update_on_repair_value", }, "instance_template": "instance_template_value", "kind": "kind_value", @@ -6853,7 +6854,8 @@ def test_insert_unary_rest(request_type): "id": 205, "instance_group": "instance_group_value", "instance_lifecycle_policy": { - "force_update_on_repair": "force_update_on_repair_value" + "default_action_on_failure": "default_action_on_failure_value", + "force_update_on_repair": "force_update_on_repair_value", }, "instance_template": "instance_template_value", "kind": "kind_value", @@ -8863,7 +8865,8 @@ def test_patch_rest(request_type): "id": 205, "instance_group": "instance_group_value", "instance_lifecycle_policy": { - "force_update_on_repair": "force_update_on_repair_value" + "default_action_on_failure": "default_action_on_failure_value", + "force_update_on_repair": "force_update_on_repair_value", }, "instance_template": "instance_template_value", "kind": "kind_value", @@ -9372,7 +9375,8 @@ def test_patch_unary_rest(request_type): "id": 205, "instance_group": "instance_group_value", "instance_lifecycle_policy": { - "force_update_on_repair": "force_update_on_repair_value" + "default_action_on_failure": "default_action_on_failure_value", + "force_update_on_repair": "force_update_on_repair_value", }, "instance_template": "instance_template_value", "kind": "kind_value", 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 new file mode 100644 index 000000000000..cd0f8902f8e3 --- /dev/null +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instant_snapshots.py @@ -0,0 +1,5610 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import Iterable +import json +import math + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import extended_operation # type: ignore +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +from google.cloud.compute_v1.services.region_instant_snapshots import ( + RegionInstantSnapshotsClient, + pagers, + transports, +) +from google.cloud.compute_v1.types import compute + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert RegionInstantSnapshotsClient._get_default_mtls_endpoint(None) is None + assert ( + RegionInstantSnapshotsClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + RegionInstantSnapshotsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + RegionInstantSnapshotsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegionInstantSnapshotsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegionInstantSnapshotsClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert RegionInstantSnapshotsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RegionInstantSnapshotsClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert RegionInstantSnapshotsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + RegionInstantSnapshotsClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert RegionInstantSnapshotsClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert RegionInstantSnapshotsClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert RegionInstantSnapshotsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionInstantSnapshotsClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert RegionInstantSnapshotsClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert RegionInstantSnapshotsClient._get_client_cert_source(None, False) is None + assert ( + RegionInstantSnapshotsClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + RegionInstantSnapshotsClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + RegionInstantSnapshotsClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + RegionInstantSnapshotsClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + RegionInstantSnapshotsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionInstantSnapshotsClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = RegionInstantSnapshotsClient._DEFAULT_UNIVERSE + default_endpoint = RegionInstantSnapshotsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = RegionInstantSnapshotsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + RegionInstantSnapshotsClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + RegionInstantSnapshotsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == RegionInstantSnapshotsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionInstantSnapshotsClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + RegionInstantSnapshotsClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == RegionInstantSnapshotsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionInstantSnapshotsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == RegionInstantSnapshotsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionInstantSnapshotsClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + RegionInstantSnapshotsClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionInstantSnapshotsClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + RegionInstantSnapshotsClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + RegionInstantSnapshotsClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + RegionInstantSnapshotsClient._get_universe_domain(None, None) + == RegionInstantSnapshotsClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + RegionInstantSnapshotsClient._get_universe_domain("", None) + 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", + [ + (RegionInstantSnapshotsClient, "rest"), + ], +) +def test_region_instant_snapshots_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.RegionInstantSnapshotsRestTransport, "rest"), + ], +) +def test_region_instant_snapshots_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (RegionInstantSnapshotsClient, "rest"), + ], +) +def test_region_instant_snapshots_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +def test_region_instant_snapshots_client_get_transport_class(): + transport = RegionInstantSnapshotsClient.get_transport_class() + available_transports = [ + transports.RegionInstantSnapshotsRestTransport, + ] + assert transport in available_transports + + transport = RegionInstantSnapshotsClient.get_transport_class("rest") + assert transport == transports.RegionInstantSnapshotsRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RegionInstantSnapshotsClient, + transports.RegionInstantSnapshotsRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + RegionInstantSnapshotsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionInstantSnapshotsClient), +) +def test_region_instant_snapshots_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(RegionInstantSnapshotsClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(RegionInstantSnapshotsClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + RegionInstantSnapshotsClient, + transports.RegionInstantSnapshotsRestTransport, + "rest", + "true", + ), + ( + RegionInstantSnapshotsClient, + transports.RegionInstantSnapshotsRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + RegionInstantSnapshotsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionInstantSnapshotsClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_region_instant_snapshots_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [RegionInstantSnapshotsClient]) +@mock.patch.object( + RegionInstantSnapshotsClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegionInstantSnapshotsClient), +) +def test_region_instant_snapshots_client_get_mtls_endpoint_and_cert_source( + client_class, +): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize("client_class", [RegionInstantSnapshotsClient]) +@mock.patch.object( + RegionInstantSnapshotsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionInstantSnapshotsClient), +) +def test_region_instant_snapshots_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = RegionInstantSnapshotsClient._DEFAULT_UNIVERSE + default_endpoint = RegionInstantSnapshotsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = RegionInstantSnapshotsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RegionInstantSnapshotsClient, + transports.RegionInstantSnapshotsRestTransport, + "rest", + ), + ], +) +def test_region_instant_snapshots_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + RegionInstantSnapshotsClient, + transports.RegionInstantSnapshotsRestTransport, + "rest", + None, + ), + ], +) +def test_region_instant_snapshots_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.DeleteRegionInstantSnapshotRequest, + dict, + ], +) +def test_delete_rest(request_type): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "instant_snapshot": "sample3", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +def test_delete_rest_required_fields( + request_type=compute.DeleteRegionInstantSnapshotRequest, +): + transport_class = transports.RegionInstantSnapshotsRestTransport + + request_init = {} + request_init["instant_snapshot"] = "" + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instantSnapshot"] = "instant_snapshot_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "instantSnapshot" in jsonified_request + assert jsonified_request["instantSnapshot"] == "instant_snapshot_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_rest_unset_required_fields(): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "instantSnapshot", + "project", + "region", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_rest_interceptors(null_interceptor): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstantSnapshotsRestInterceptor(), + ) + client = RegionInstantSnapshotsClient(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.RegionInstantSnapshotsRestInterceptor, "post_delete" + ) as post, mock.patch.object( + transports.RegionInstantSnapshotsRestInterceptor, "pre_delete" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.DeleteRegionInstantSnapshotRequest.pb( + compute.DeleteRegionInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.DeleteRegionInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.delete( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_rest_bad_request( + transport: str = "rest", request_type=compute.DeleteRegionInstantSnapshotRequest +): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "instant_snapshot": "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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete(request) + + +def test_delete_rest_flattened(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "instant_snapshot": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + instant_snapshot="instant_snapshot_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/instantSnapshots/{instant_snapshot}" + % client.transport._host, + args[1], + ) + + +def test_delete_rest_flattened_error(transport: str = "rest"): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete( + compute.DeleteRegionInstantSnapshotRequest(), + project="project_value", + region="region_value", + instant_snapshot="instant_snapshot_value", + ) + + +def test_delete_rest_error(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.DeleteRegionInstantSnapshotRequest, + dict, + ], +) +def test_delete_unary_rest(request_type): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "instant_snapshot": "sample3", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_unary(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + + +def test_delete_unary_rest_required_fields( + request_type=compute.DeleteRegionInstantSnapshotRequest, +): + transport_class = transports.RegionInstantSnapshotsRestTransport + + request_init = {} + request_init["instant_snapshot"] = "" + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instantSnapshot"] = "instant_snapshot_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "instantSnapshot" in jsonified_request + assert jsonified_request["instantSnapshot"] == "instant_snapshot_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_unary_rest_unset_required_fields(): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "instantSnapshot", + "project", + "region", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_unary_rest_interceptors(null_interceptor): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstantSnapshotsRestInterceptor(), + ) + client = RegionInstantSnapshotsClient(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.RegionInstantSnapshotsRestInterceptor, "post_delete" + ) as post, mock.patch.object( + transports.RegionInstantSnapshotsRestInterceptor, "pre_delete" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.DeleteRegionInstantSnapshotRequest.pb( + compute.DeleteRegionInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.DeleteRegionInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.delete_unary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_unary_rest_bad_request( + transport: str = "rest", request_type=compute.DeleteRegionInstantSnapshotRequest +): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "instant_snapshot": "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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_unary(request) + + +def test_delete_unary_rest_flattened(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "instant_snapshot": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + instant_snapshot="instant_snapshot_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/instantSnapshots/{instant_snapshot}" + % client.transport._host, + args[1], + ) + + +def test_delete_unary_rest_flattened_error(transport: str = "rest"): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_unary( + compute.DeleteRegionInstantSnapshotRequest(), + project="project_value", + region="region_value", + instant_snapshot="instant_snapshot_value", + ) + + +def test_delete_unary_rest_error(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetRegionInstantSnapshotRequest, + dict, + ], +) +def test_get_rest(request_type): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "instant_snapshot": "sample3", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.InstantSnapshot( + architecture="architecture_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + disk_size_gb=1261, + id=205, + kind="kind_value", + label_fingerprint="label_fingerprint_value", + name="name_value", + region="region_value", + satisfies_pzi=True, + satisfies_pzs=True, + self_link="self_link_value", + self_link_with_id="self_link_with_id_value", + source_disk="source_disk_value", + source_disk_id="source_disk_id_value", + status="status_value", + zone="zone_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 = compute.InstantSnapshot.pb(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(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.InstantSnapshot) + assert response.architecture == "architecture_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.disk_size_gb == 1261 + assert response.id == 205 + assert response.kind == "kind_value" + assert response.label_fingerprint == "label_fingerprint_value" + assert response.name == "name_value" + assert response.region == "region_value" + assert response.satisfies_pzi is True + assert response.satisfies_pzs is True + assert response.self_link == "self_link_value" + assert response.self_link_with_id == "self_link_with_id_value" + assert response.source_disk == "source_disk_value" + assert response.source_disk_id == "source_disk_id_value" + assert response.status == "status_value" + assert response.zone == "zone_value" + + +def test_get_rest_required_fields(request_type=compute.GetRegionInstantSnapshotRequest): + transport_class = transports.RegionInstantSnapshotsRestTransport + + request_init = {} + request_init["instant_snapshot"] = "" + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instantSnapshot"] = "instant_snapshot_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "instantSnapshot" in jsonified_request + assert jsonified_request["instantSnapshot"] == "instant_snapshot_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.InstantSnapshot() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.InstantSnapshot.pb(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(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_rest_unset_required_fields(): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "instantSnapshot", + "project", + "region", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstantSnapshotsRestInterceptor(), + ) + client = RegionInstantSnapshotsClient(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.RegionInstantSnapshotsRestInterceptor, "post_get" + ) as post, mock.patch.object( + transports.RegionInstantSnapshotsRestInterceptor, "pre_get" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.GetRegionInstantSnapshotRequest.pb( + compute.GetRegionInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.InstantSnapshot.to_json( + compute.InstantSnapshot() + ) + + request = compute.GetRegionInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.InstantSnapshot() + + client.get( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_rest_bad_request( + transport: str = "rest", request_type=compute.GetRegionInstantSnapshotRequest +): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "instant_snapshot": "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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get(request) + + +def test_get_rest_flattened(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.InstantSnapshot() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "instant_snapshot": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + instant_snapshot="instant_snapshot_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.InstantSnapshot.pb(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(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/instantSnapshots/{instant_snapshot}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get( + compute.GetRegionInstantSnapshotRequest(), + project="project_value", + region="region_value", + instant_snapshot="instant_snapshot_value", + ) + + +def test_get_rest_error(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetIamPolicyRegionInstantSnapshotRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy( + etag="etag_value", + iam_owned=True, + version=774, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Policy) + assert response.etag == "etag_value" + assert response.iam_owned is True + assert response.version == 774 + + +def test_get_iam_policy_rest_required_fields( + request_type=compute.GetIamPolicyRegionInstantSnapshotRequest, +): + transport_class = transports.RegionInstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_iam_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("options_requested_policy_version",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_iam_policy(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("optionsRequestedPolicyVersion",)) + & set( + ( + "project", + "region", + "resource", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstantSnapshotsRestInterceptor(), + ) + client = RegionInstantSnapshotsClient(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.RegionInstantSnapshotsRestInterceptor, "post_get_iam_policy" + ) as post, mock.patch.object( + transports.RegionInstantSnapshotsRestInterceptor, "pre_get_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.GetIamPolicyRegionInstantSnapshotRequest.pb( + compute.GetIamPolicyRegionInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Policy.to_json(compute.Policy()) + + request = compute.GetIamPolicyRegionInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Policy() + + client.get_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request( + transport: str = "rest", + request_type=compute.GetIamPolicyRegionInstantSnapshotRequest, +): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "resource": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + resource="resource_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/instantSnapshots/{resource}/getIamPolicy" + % client.transport._host, + args[1], + ) + + +def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_iam_policy( + compute.GetIamPolicyRegionInstantSnapshotRequest(), + project="project_value", + region="region_value", + resource="resource_value", + ) + + +def test_get_iam_policy_rest_error(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.InsertRegionInstantSnapshotRequest, + dict, + ], +) +def test_insert_rest(request_type): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request_init["instant_snapshot_resource"] = { + "architecture": "architecture_value", + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "disk_size_gb": 1261, + "id": 205, + "kind": "kind_value", + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + "name": "name_value", + "region": "region_value", + "resource_status": {"storage_size_bytes": 1941}, + "satisfies_pzi": True, + "satisfies_pzs": True, + "self_link": "self_link_value", + "self_link_with_id": "self_link_with_id_value", + "source_disk": "source_disk_value", + "source_disk_id": "source_disk_id_value", + "status": "status_value", + "zone": "zone_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.InsertRegionInstantSnapshotRequest.meta.fields[ + "instant_snapshot_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "instant_snapshot_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["instant_snapshot_resource"][field]) + ): + del request_init["instant_snapshot_resource"][field][i][subfield] + else: + del request_init["instant_snapshot_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.insert(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +def test_insert_rest_required_fields( + request_type=compute.InsertRegionInstantSnapshotRequest, +): + transport_class = transports.RegionInstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.insert(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_insert_rest_unset_required_fields(): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "instantSnapshotResource", + "project", + "region", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_rest_interceptors(null_interceptor): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstantSnapshotsRestInterceptor(), + ) + client = RegionInstantSnapshotsClient(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.RegionInstantSnapshotsRestInterceptor, "post_insert" + ) as post, mock.patch.object( + transports.RegionInstantSnapshotsRestInterceptor, "pre_insert" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.InsertRegionInstantSnapshotRequest.pb( + compute.InsertRegionInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.InsertRegionInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.insert( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_insert_rest_bad_request( + transport: str = "rest", request_type=compute.InsertRegionInstantSnapshotRequest +): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.insert(request) + + +def test_insert_rest_flattened(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + instant_snapshot_resource=compute.InstantSnapshot( + architecture="architecture_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.insert(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/instantSnapshots" + % client.transport._host, + args[1], + ) + + +def test_insert_rest_flattened_error(transport: str = "rest"): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.insert( + compute.InsertRegionInstantSnapshotRequest(), + project="project_value", + region="region_value", + instant_snapshot_resource=compute.InstantSnapshot( + architecture="architecture_value" + ), + ) + + +def test_insert_rest_error(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.InsertRegionInstantSnapshotRequest, + dict, + ], +) +def test_insert_unary_rest(request_type): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request_init["instant_snapshot_resource"] = { + "architecture": "architecture_value", + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "disk_size_gb": 1261, + "id": 205, + "kind": "kind_value", + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + "name": "name_value", + "region": "region_value", + "resource_status": {"storage_size_bytes": 1941}, + "satisfies_pzi": True, + "satisfies_pzs": True, + "self_link": "self_link_value", + "self_link_with_id": "self_link_with_id_value", + "source_disk": "source_disk_value", + "source_disk_id": "source_disk_id_value", + "status": "status_value", + "zone": "zone_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.InsertRegionInstantSnapshotRequest.meta.fields[ + "instant_snapshot_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "instant_snapshot_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["instant_snapshot_resource"][field]) + ): + del request_init["instant_snapshot_resource"][field][i][subfield] + else: + del request_init["instant_snapshot_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.insert_unary(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + + +def test_insert_unary_rest_required_fields( + request_type=compute.InsertRegionInstantSnapshotRequest, +): + transport_class = transports.RegionInstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.insert_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_insert_unary_rest_unset_required_fields(): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "instantSnapshotResource", + "project", + "region", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_unary_rest_interceptors(null_interceptor): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstantSnapshotsRestInterceptor(), + ) + client = RegionInstantSnapshotsClient(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.RegionInstantSnapshotsRestInterceptor, "post_insert" + ) as post, mock.patch.object( + transports.RegionInstantSnapshotsRestInterceptor, "pre_insert" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.InsertRegionInstantSnapshotRequest.pb( + compute.InsertRegionInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.InsertRegionInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.insert_unary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_insert_unary_rest_bad_request( + transport: str = "rest", request_type=compute.InsertRegionInstantSnapshotRequest +): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.insert_unary(request) + + +def test_insert_unary_rest_flattened(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + instant_snapshot_resource=compute.InstantSnapshot( + architecture="architecture_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.insert_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/instantSnapshots" + % client.transport._host, + args[1], + ) + + +def test_insert_unary_rest_flattened_error(transport: str = "rest"): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.insert_unary( + compute.InsertRegionInstantSnapshotRequest(), + project="project_value", + region="region_value", + instant_snapshot_resource=compute.InstantSnapshot( + architecture="architecture_value" + ), + ) + + +def test_insert_unary_rest_error(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ListRegionInstantSnapshotsRequest, + dict, + ], +) +def test_list_rest(request_type): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.InstantSnapshotList( + id="id_value", + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.InstantSnapshotList.pb(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(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPager) + assert response.id == "id_value" + assert response.kind == "kind_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + + +def test_list_rest_required_fields( + request_type=compute.ListRegionInstantSnapshotsRequest, +): + transport_class = transports.RegionInstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "max_results", + "order_by", + "page_token", + "return_partial_success", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.InstantSnapshotList() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.InstantSnapshotList.pb(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(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_rest_unset_required_fields(): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set( + ( + "project", + "region", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rest_interceptors(null_interceptor): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstantSnapshotsRestInterceptor(), + ) + client = RegionInstantSnapshotsClient(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.RegionInstantSnapshotsRestInterceptor, "post_list" + ) as post, mock.patch.object( + transports.RegionInstantSnapshotsRestInterceptor, "pre_list" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.ListRegionInstantSnapshotsRequest.pb( + compute.ListRegionInstantSnapshotsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.InstantSnapshotList.to_json( + compute.InstantSnapshotList() + ) + + request = compute.ListRegionInstantSnapshotsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.InstantSnapshotList() + + client.list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_rest_bad_request( + transport: str = "rest", request_type=compute.ListRegionInstantSnapshotsRequest +): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list(request) + + +def test_list_rest_flattened(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.InstantSnapshotList() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.InstantSnapshotList.pb(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(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/instantSnapshots" + % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list( + compute.ListRegionInstantSnapshotsRequest(), + project="project_value", + region="region_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + compute.InstantSnapshotList( + items=[ + compute.InstantSnapshot(), + compute.InstantSnapshot(), + compute.InstantSnapshot(), + ], + next_page_token="abc", + ), + compute.InstantSnapshotList( + items=[], + next_page_token="def", + ), + compute.InstantSnapshotList( + items=[ + compute.InstantSnapshot(), + ], + next_page_token="ghi", + ), + compute.InstantSnapshotList( + items=[ + compute.InstantSnapshot(), + compute.InstantSnapshot(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.InstantSnapshotList.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"project": "sample1", "region": "sample2"} + + pager = client.list(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.InstantSnapshot) for i in results) + + pages = list(client.list(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + compute.SetIamPolicyRegionInstantSnapshotRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource": "sample3"} + request_init["region_set_policy_request_resource"] = { + "bindings": [ + { + "binding_id": "binding_id_value", + "condition": { + "description": "description_value", + "expression": "expression_value", + "location": "location_value", + "title": "title_value", + }, + "members": ["members_value1", "members_value2"], + "role": "role_value", + } + ], + "etag": "etag_value", + "policy": { + "audit_configs": [ + { + "audit_log_configs": [ + { + "exempted_members": [ + "exempted_members_value1", + "exempted_members_value2", + ], + "ignore_child_exemptions": True, + "log_type": "log_type_value", + } + ], + "exempted_members": [ + "exempted_members_value1", + "exempted_members_value2", + ], + "service": "service_value", + } + ], + "bindings": {}, + "etag": "etag_value", + "iam_owned": True, + "rules": [ + { + "action": "action_value", + "conditions": [ + { + "iam": "iam_value", + "op": "op_value", + "svc": "svc_value", + "sys": "sys_value", + "values": ["values_value1", "values_value2"], + } + ], + "description": "description_value", + "ins": ["ins_value1", "ins_value2"], + "log_configs": [ + { + "cloud_audit": { + "authorization_logging_options": { + "permission_type": "permission_type_value" + }, + "log_name": "log_name_value", + }, + "counter": { + "custom_fields": [ + {"name": "name_value", "value": "value_value"} + ], + "field": "field_value", + "metric": "metric_value", + }, + "data_access": {"log_mode": "log_mode_value"}, + } + ], + "not_ins": ["not_ins_value1", "not_ins_value2"], + "permissions": ["permissions_value1", "permissions_value2"], + } + ], + "version": 774, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.SetIamPolicyRegionInstantSnapshotRequest.meta.fields[ + "region_set_policy_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "region_set_policy_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["region_set_policy_request_resource"][field]) + ): + del request_init["region_set_policy_request_resource"][field][i][ + subfield + ] + else: + del request_init["region_set_policy_request_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy( + etag="etag_value", + iam_owned=True, + version=774, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Policy) + assert response.etag == "etag_value" + assert response.iam_owned is True + assert response.version == 774 + + +def test_set_iam_policy_rest_required_fields( + request_type=compute.SetIamPolicyRegionInstantSnapshotRequest, +): + transport_class = transports.RegionInstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.set_iam_policy(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "project", + "region", + "regionSetPolicyRequestResource", + "resource", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstantSnapshotsRestInterceptor(), + ) + client = RegionInstantSnapshotsClient(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.RegionInstantSnapshotsRestInterceptor, "post_set_iam_policy" + ) as post, mock.patch.object( + transports.RegionInstantSnapshotsRestInterceptor, "pre_set_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.SetIamPolicyRegionInstantSnapshotRequest.pb( + compute.SetIamPolicyRegionInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Policy.to_json(compute.Policy()) + + request = compute.SetIamPolicyRegionInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Policy() + + client.set_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request( + transport: str = "rest", + request_type=compute.SetIamPolicyRegionInstantSnapshotRequest, +): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "resource": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + resource="resource_value", + region_set_policy_request_resource=compute.RegionSetPolicyRequest( + bindings=[compute.Binding(binding_id="binding_id_value")] + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.set_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/instantSnapshots/{resource}/setIamPolicy" + % client.transport._host, + args[1], + ) + + +def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + compute.SetIamPolicyRegionInstantSnapshotRequest(), + project="project_value", + region="region_value", + resource="resource_value", + region_set_policy_request_resource=compute.RegionSetPolicyRequest( + bindings=[compute.Binding(binding_id="binding_id_value")] + ), + ) + + +def test_set_iam_policy_rest_error(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.SetLabelsRegionInstantSnapshotRequest, + dict, + ], +) +def test_set_labels_rest(request_type): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource": "sample3"} + request_init["region_set_labels_request_resource"] = { + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.SetLabelsRegionInstantSnapshotRequest.meta.fields[ + "region_set_labels_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "region_set_labels_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["region_set_labels_request_resource"][field]) + ): + del request_init["region_set_labels_request_resource"][field][i][ + subfield + ] + else: + del request_init["region_set_labels_request_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_labels(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +def test_set_labels_rest_required_fields( + request_type=compute.SetLabelsRegionInstantSnapshotRequest, +): + transport_class = transports.RegionInstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_labels._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_labels._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.set_labels(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_labels_rest_unset_required_fields(): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_labels._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "region", + "regionSetLabelsRequestResource", + "resource", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_labels_rest_interceptors(null_interceptor): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstantSnapshotsRestInterceptor(), + ) + client = RegionInstantSnapshotsClient(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.RegionInstantSnapshotsRestInterceptor, "post_set_labels" + ) as post, mock.patch.object( + transports.RegionInstantSnapshotsRestInterceptor, "pre_set_labels" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.SetLabelsRegionInstantSnapshotRequest.pb( + compute.SetLabelsRegionInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.SetLabelsRegionInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.set_labels( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_labels_rest_bad_request( + transport: str = "rest", request_type=compute.SetLabelsRegionInstantSnapshotRequest +): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_labels(request) + + +def test_set_labels_rest_flattened(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "resource": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + resource="resource_value", + region_set_labels_request_resource=compute.RegionSetLabelsRequest( + label_fingerprint="label_fingerprint_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.set_labels(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/instantSnapshots/{resource}/setLabels" + % client.transport._host, + args[1], + ) + + +def test_set_labels_rest_flattened_error(transport: str = "rest"): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_labels( + compute.SetLabelsRegionInstantSnapshotRequest(), + project="project_value", + region="region_value", + resource="resource_value", + region_set_labels_request_resource=compute.RegionSetLabelsRequest( + label_fingerprint="label_fingerprint_value" + ), + ) + + +def test_set_labels_rest_error(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.SetLabelsRegionInstantSnapshotRequest, + dict, + ], +) +def test_set_labels_unary_rest(request_type): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource": "sample3"} + request_init["region_set_labels_request_resource"] = { + "label_fingerprint": "label_fingerprint_value", + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.SetLabelsRegionInstantSnapshotRequest.meta.fields[ + "region_set_labels_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "region_set_labels_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["region_set_labels_request_resource"][field]) + ): + del request_init["region_set_labels_request_resource"][field][i][ + subfield + ] + else: + del request_init["region_set_labels_request_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_labels_unary(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.Operation) + + +def test_set_labels_unary_rest_required_fields( + request_type=compute.SetLabelsRegionInstantSnapshotRequest, +): + transport_class = transports.RegionInstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_labels._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_labels._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.set_labels_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_labels_unary_rest_unset_required_fields(): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_labels._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "region", + "regionSetLabelsRequestResource", + "resource", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_labels_unary_rest_interceptors(null_interceptor): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstantSnapshotsRestInterceptor(), + ) + client = RegionInstantSnapshotsClient(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.RegionInstantSnapshotsRestInterceptor, "post_set_labels" + ) as post, mock.patch.object( + transports.RegionInstantSnapshotsRestInterceptor, "pre_set_labels" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.SetLabelsRegionInstantSnapshotRequest.pb( + compute.SetLabelsRegionInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.Operation.to_json(compute.Operation()) + + request = compute.SetLabelsRegionInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + + client.set_labels_unary( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_labels_unary_rest_bad_request( + transport: str = "rest", request_type=compute.SetLabelsRegionInstantSnapshotRequest +): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_labels_unary(request) + + +def test_set_labels_unary_rest_flattened(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "resource": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + resource="resource_value", + region_set_labels_request_resource=compute.RegionSetLabelsRequest( + label_fingerprint="label_fingerprint_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.set_labels_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/instantSnapshots/{resource}/setLabels" + % client.transport._host, + args[1], + ) + + +def test_set_labels_unary_rest_flattened_error(transport: str = "rest"): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_labels_unary( + compute.SetLabelsRegionInstantSnapshotRequest(), + project="project_value", + region="region_value", + resource="resource_value", + region_set_labels_request_resource=compute.RegionSetLabelsRequest( + label_fingerprint="label_fingerprint_value" + ), + ) + + +def test_set_labels_unary_rest_error(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.TestIamPermissionsRegionInstantSnapshotRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource": "sample3"} + request_init["test_permissions_request_resource"] = { + "permissions": ["permissions_value1", "permissions_value2"] + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.TestIamPermissionsRegionInstantSnapshotRequest.meta.fields[ + "test_permissions_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "test_permissions_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["test_permissions_request_resource"][field]) + ): + del request_init["test_permissions_request_resource"][field][i][ + subfield + ] + else: + del request_init["test_permissions_request_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.TestPermissionsResponse( + permissions=["permissions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.TestPermissionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.TestPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_rest_required_fields( + request_type=compute.TestIamPermissionsRegionInstantSnapshotRequest, +): + transport_class = transports.RegionInstantSnapshotsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.TestPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.TestPermissionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.test_iam_permissions(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "project", + "region", + "resource", + "testPermissionsRequestResource", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionInstantSnapshotsRestInterceptor(), + ) + client = RegionInstantSnapshotsClient(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.RegionInstantSnapshotsRestInterceptor, "post_test_iam_permissions" + ) as post, mock.patch.object( + transports.RegionInstantSnapshotsRestInterceptor, "pre_test_iam_permissions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = compute.TestIamPermissionsRegionInstantSnapshotRequest.pb( + compute.TestIamPermissionsRegionInstantSnapshotRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = compute.TestPermissionsResponse.to_json( + compute.TestPermissionsResponse() + ) + + request = compute.TestIamPermissionsRegionInstantSnapshotRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.TestPermissionsResponse() + + client.test_iam_permissions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request( + transport: str = "rest", + request_type=compute.TestIamPermissionsRegionInstantSnapshotRequest, +): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.TestPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "resource": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + resource="resource_value", + test_permissions_request_resource=compute.TestPermissionsRequest( + permissions=["permissions_value"] + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.TestPermissionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.test_iam_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/regions/{region}/instantSnapshots/{resource}/testIamPermissions" + % client.transport._host, + args[1], + ) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + compute.TestIamPermissionsRegionInstantSnapshotRequest(), + project="project_value", + region="region_value", + resource="resource_value", + test_permissions_request_resource=compute.TestPermissionsRequest( + permissions=["permissions_value"] + ), + ) + + +def test_test_iam_permissions_rest_error(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionInstantSnapshotsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RegionInstantSnapshotsClient( + 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 = RegionInstantSnapshotsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionInstantSnapshotsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegionInstantSnapshotsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RegionInstantSnapshotsClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionInstantSnapshotsRestTransport, + ], +) +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() + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_transport_kind(transport_name): + transport = RegionInstantSnapshotsClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_region_instant_snapshots_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RegionInstantSnapshotsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_region_instant_snapshots_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1.services.region_instant_snapshots.transports.RegionInstantSnapshotsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RegionInstantSnapshotsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "delete", + "get", + "get_iam_policy", + "insert", + "list", + "set_iam_policy", + "set_labels", + "test_iam_permissions", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_region_instant_snapshots_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.compute_v1.services.region_instant_snapshots.transports.RegionInstantSnapshotsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionInstantSnapshotsTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_region_instant_snapshots_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.compute_v1.services.region_instant_snapshots.transports.RegionInstantSnapshotsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionInstantSnapshotsTransport() + adc.assert_called_once() + + +def test_region_instant_snapshots_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RegionInstantSnapshotsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_region_instant_snapshots_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.RegionInstantSnapshotsRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_region_instant_snapshots_host_no_port(transport_name): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_region_instant_snapshots_host_with_port(transport_name): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_region_instant_snapshots_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RegionInstantSnapshotsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RegionInstantSnapshotsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.delete._session + session2 = client2.transport.delete._session + assert session1 != session2 + session1 = client1.transport.get._session + session2 = client2.transport.get._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.insert._session + session2 = client2.transport.insert._session + assert session1 != session2 + session1 = client1.transport.list._session + session2 = client2.transport.list._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.set_labels._session + session2 = client2.transport.set_labels._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = RegionInstantSnapshotsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RegionInstantSnapshotsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RegionInstantSnapshotsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = RegionInstantSnapshotsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RegionInstantSnapshotsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RegionInstantSnapshotsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = RegionInstantSnapshotsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RegionInstantSnapshotsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RegionInstantSnapshotsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = RegionInstantSnapshotsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RegionInstantSnapshotsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RegionInstantSnapshotsClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = RegionInstantSnapshotsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RegionInstantSnapshotsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RegionInstantSnapshotsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.RegionInstantSnapshotsTransport, "_prep_wrapped_messages" + ) as prep: + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.RegionInstantSnapshotsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = RegionInstantSnapshotsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close(): + transports = { + "rest": "_session", + } + + for transport, close_name in transports.items(): + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + ] + for transport in transports: + client = RegionInstantSnapshotsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (RegionInstantSnapshotsClient, transports.RegionInstantSnapshotsRestTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_snapshots.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_snapshots.py index 0ba3ad8323a8..cc40bd2f0991 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 @@ -1584,6 +1584,8 @@ def test_get_rest(request_type): source_disk="source_disk_value", source_disk_for_recovery_checkpoint="source_disk_for_recovery_checkpoint_value", source_disk_id="source_disk_id_value", + source_instant_snapshot="source_instant_snapshot_value", + source_instant_snapshot_id="source_instant_snapshot_id_value", source_snapshot_schedule_policy="source_snapshot_schedule_policy_value", source_snapshot_schedule_policy_id="source_snapshot_schedule_policy_id_value", status="status_value", @@ -1631,6 +1633,8 @@ def test_get_rest(request_type): == "source_disk_for_recovery_checkpoint_value" ) assert response.source_disk_id == "source_disk_id_value" + assert response.source_instant_snapshot == "source_instant_snapshot_value" + assert response.source_instant_snapshot_id == "source_instant_snapshot_id_value" assert ( response.source_snapshot_schedule_policy == "source_snapshot_schedule_policy_value" @@ -2210,6 +2214,9 @@ def test_insert_rest(request_type): "source_disk_encryption_key": {}, "source_disk_for_recovery_checkpoint": "source_disk_for_recovery_checkpoint_value", "source_disk_id": "source_disk_id_value", + "source_instant_snapshot": "source_instant_snapshot_value", + "source_instant_snapshot_encryption_key": {}, + "source_instant_snapshot_id": "source_instant_snapshot_id_value", "source_snapshot_schedule_policy": "source_snapshot_schedule_policy_value", "source_snapshot_schedule_policy_id": "source_snapshot_schedule_policy_id_value", "status": "status_value", @@ -2632,6 +2639,9 @@ def test_insert_unary_rest(request_type): "source_disk_encryption_key": {}, "source_disk_for_recovery_checkpoint": "source_disk_for_recovery_checkpoint_value", "source_disk_id": "source_disk_id_value", + "source_instant_snapshot": "source_instant_snapshot_value", + "source_instant_snapshot_encryption_key": {}, + "source_instant_snapshot_id": "source_instant_snapshot_id_value", "source_snapshot_schedule_policy": "source_snapshot_schedule_policy_value", "source_snapshot_schedule_policy_id": "source_snapshot_schedule_policy_id_value", "status": "status_value", 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 111b9698ee76..d4b139ce9b42 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 @@ -1970,6 +1970,7 @@ def test_get_rest(request_type): return_value = compute.VpnGateway( creation_timestamp="creation_timestamp_value", description="description_value", + gateway_ip_version="gateway_ip_version_value", id=205, kind="kind_value", label_fingerprint="label_fingerprint_value", @@ -1995,6 +1996,7 @@ def test_get_rest(request_type): assert isinstance(response, compute.VpnGateway) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" + assert response.gateway_ip_version == "gateway_ip_version_value" assert response.id == 205 assert response.kind == "kind_value" assert response.label_fingerprint == "label_fingerprint_value" @@ -2558,6 +2560,7 @@ def test_insert_rest(request_type): request_init["vpn_gateway_resource"] = { "creation_timestamp": "creation_timestamp_value", "description": "description_value", + "gateway_ip_version": "gateway_ip_version_value", "id": 205, "kind": "kind_value", "label_fingerprint": "label_fingerprint_value", @@ -2572,6 +2575,7 @@ def test_insert_rest(request_type): "id": 205, "interconnect_attachment": "interconnect_attachment_value", "ip_address": "ip_address_value", + "ipv6_address": "ipv6_address_value", } ], } @@ -2976,6 +2980,7 @@ def test_insert_unary_rest(request_type): request_init["vpn_gateway_resource"] = { "creation_timestamp": "creation_timestamp_value", "description": "description_value", + "gateway_ip_version": "gateway_ip_version_value", "id": 205, "kind": "kind_value", "label_fingerprint": "label_fingerprint_value", @@ -2990,6 +2995,7 @@ def test_insert_unary_rest(request_type): "id": 205, "interconnect_attachment": "interconnect_attachment_value", "ip_address": "ip_address_value", + "ipv6_address": "ipv6_address_value", } ], } diff --git a/packages/google-cloud-confidentialcomputing/CHANGELOG.md b/packages/google-cloud-confidentialcomputing/CHANGELOG.md index 2f912a37fc74..a7422ff10caa 100644 --- a/packages/google-cloud-confidentialcomputing/CHANGELOG.md +++ b/packages/google-cloud-confidentialcomputing/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.4.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-confidentialcomputing-v0.4.6...google-cloud-confidentialcomputing-v0.4.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [0.4.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-confidentialcomputing-v0.4.5...google-cloud-confidentialcomputing-v0.4.6) (2024-02-22) 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 7c932adae91d..05392921a87c 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.6" # {x-release-please-version} +__version__ = "0.4.7" # {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 7c932adae91d..05392921a87c 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.6" # {x-release-please-version} +__version__ = "0.4.7" # {x-release-please-version} 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 71c973b9ec13..15b2f5749cbe 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.6" + "version": "0.4.7" }, "snippets": [ { diff --git a/packages/google-cloud-confidentialcomputing/setup.py b/packages/google-cloud-confidentialcomputing/setup.py index 108adf51c261..1f9180d16041 100644 --- a/packages/google-cloud-confidentialcomputing/setup.py +++ b/packages/google-cloud-confidentialcomputing/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-config/CHANGELOG.md b/packages/google-cloud-config/CHANGELOG.md index 3e61934bd535..ab850ea51410 100644 --- a/packages/google-cloud-config/CHANGELOG.md +++ b/packages/google-cloud-config/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-config-v0.1.6...google-cloud-config-v0.1.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [0.1.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-config-v0.1.5...google-cloud-config-v0.1.6) (2024-02-22) 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 60402a4567d1..e34e491c76d0 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.6" # {x-release-please-version} +__version__ = "0.1.7" # {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 60402a4567d1..e34e491c76d0 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.6" # {x-release-please-version} +__version__ = "0.1.7" # {x-release-please-version} 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 7f749dc01cb8..62990e9edba7 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.6" + "version": "0.1.7" }, "snippets": [ { diff --git a/packages/google-cloud-config/setup.py b/packages/google-cloud-config/setup.py index a16dccea1029..0d07a2f85d98 100644 --- a/packages/google-cloud-config/setup.py +++ b/packages/google-cloud-config/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-contact-center-insights/CHANGELOG.md b/packages/google-cloud-contact-center-insights/CHANGELOG.md index 3103e278bcf2..3445be0dca5a 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.17.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-contact-center-insights-v1.17.2...google-cloud-contact-center-insights-v1.17.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [1.17.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-contact-center-insights-v1.17.1...google-cloud-contact-center-insights-v1.17.2) (2024-02-22) 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 1e0921955b0c..3639317ee4f0 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.17.2" # {x-release-please-version} +__version__ = "1.17.3" # {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 1e0921955b0c..3639317ee4f0 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.17.2" # {x-release-please-version} +__version__ = "1.17.3" # {x-release-please-version} 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 b45517e73ae0..c34f03a71a18 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.17.2" + "version": "1.17.3" }, "snippets": [ { diff --git a/packages/google-cloud-contact-center-insights/setup.py b/packages/google-cloud-contact-center-insights/setup.py index feac0e7dbae1..5aa989eeaa37 100644 --- a/packages/google-cloud-contact-center-insights/setup.py +++ b/packages/google-cloud-contact-center-insights/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-container/CHANGELOG.md b/packages/google-cloud-container/CHANGELOG.md index 82ef913743e3..9a865b74963d 100644 --- a/packages/google-cloud-container/CHANGELOG.md +++ b/packages/google-cloud-container/CHANGELOG.md @@ -4,6 +4,24 @@ [1]: https://pypi.org/project/google-cloud-container/#history +## [2.42.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-container-v2.41.0...google-cloud-container-v2.42.0) (2024-03-04) + + +### Features + +* add API to enable Provisioning Request API on existing nodepools ([43e63be](https://github.com/googleapis/google-cloud-python/commit/43e63be479ab80d4d3be2c47c3be530db4d30993)) +* add secondary boot disks field to NodePool API ([43e63be](https://github.com/googleapis/google-cloud-python/commit/43e63be479ab80d4d3be2c47c3be530db4d30993)) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([43e63be](https://github.com/googleapis/google-cloud-python/commit/43e63be479ab80d4d3be2c47c3be530db4d30993)) + + +### Documentation + +* Update comment for field `enable_confidential_storage` in message `google.container.v1beta1.NodeConfig` ([43e63be](https://github.com/googleapis/google-cloud-python/commit/43e63be479ab80d4d3be2c47c3be530db4d30993)) + ## [2.41.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-container-v2.40.0...google-cloud-container-v2.41.0) (2024-02-22) diff --git a/packages/google-cloud-container/google/cloud/container/gapic_version.py b/packages/google-cloud-container/google/cloud/container/gapic_version.py index cc337c45cd67..9e1f3252167d 100644 --- a/packages/google-cloud-container/google/cloud/container/gapic_version.py +++ b/packages/google-cloud-container/google/cloud/container/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.41.0" # {x-release-please-version} +__version__ = "2.42.0" # {x-release-please-version} diff --git a/packages/google-cloud-container/google/cloud/container_v1/gapic_version.py b/packages/google-cloud-container/google/cloud/container_v1/gapic_version.py index cc337c45cd67..9e1f3252167d 100644 --- a/packages/google-cloud-container/google/cloud/container_v1/gapic_version.py +++ b/packages/google-cloud-container/google/cloud/container_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.41.0" # {x-release-please-version} +__version__ = "2.42.0" # {x-release-please-version} diff --git a/packages/google-cloud-container/google/cloud/container_v1beta1/__init__.py b/packages/google-cloud-container/google/cloud/container_v1beta1/__init__.py index 0dca9d155e6a..445df45af37c 100644 --- a/packages/google-cloud-container/google/cloud/container_v1beta1/__init__.py +++ b/packages/google-cloud-container/google/cloud/container_v1beta1/__init__.py @@ -159,6 +159,7 @@ ResourceUsageExportConfig, RollbackNodePoolUpgradeRequest, SandboxConfig, + SecondaryBootDisk, SecurityBulletinEvent, SecurityPostureConfig, ServerConfig, @@ -346,6 +347,7 @@ "ResourceUsageExportConfig", "RollbackNodePoolUpgradeRequest", "SandboxConfig", + "SecondaryBootDisk", "SecurityBulletinEvent", "SecurityPostureConfig", "ServerConfig", diff --git a/packages/google-cloud-container/google/cloud/container_v1beta1/gapic_version.py b/packages/google-cloud-container/google/cloud/container_v1beta1/gapic_version.py index cc337c45cd67..9e1f3252167d 100644 --- a/packages/google-cloud-container/google/cloud/container_v1beta1/gapic_version.py +++ b/packages/google-cloud-container/google/cloud/container_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.41.0" # {x-release-please-version} +__version__ = "2.42.0" # {x-release-please-version} diff --git a/packages/google-cloud-container/google/cloud/container_v1beta1/types/__init__.py b/packages/google-cloud-container/google/cloud/container_v1beta1/types/__init__.py index 4837bfe12f88..762008fff2cb 100644 --- a/packages/google-cloud-container/google/cloud/container_v1beta1/types/__init__.py +++ b/packages/google-cloud-container/google/cloud/container_v1beta1/types/__init__.py @@ -153,6 +153,7 @@ ResourceUsageExportConfig, RollbackNodePoolUpgradeRequest, SandboxConfig, + SecondaryBootDisk, SecurityBulletinEvent, SecurityPostureConfig, ServerConfig, @@ -334,6 +335,7 @@ "ResourceUsageExportConfig", "RollbackNodePoolUpgradeRequest", "SandboxConfig", + "SecondaryBootDisk", "SecurityBulletinEvent", "SecurityPostureConfig", "ServerConfig", diff --git a/packages/google-cloud-container/google/cloud/container_v1beta1/types/cluster_service.py b/packages/google-cloud-container/google/cloud/container_v1beta1/types/cluster_service.py index b0d85e36a70b..21426afa9f22 100644 --- a/packages/google-cloud-container/google/cloud/container_v1beta1/types/cluster_service.py +++ b/packages/google-cloud-container/google/cloud/container_v1beta1/types/cluster_service.py @@ -210,6 +210,7 @@ "Fleet", "ResourceManagerTags", "EnterpriseConfig", + "SecondaryBootDisk", }, ) @@ -723,10 +724,10 @@ class NodeConfig(proto.Message): A map of resource manager tag keys and values to be attached to the nodes. enable_confidential_storage (bool): - Optional. Enable confidential storage on Hyperdisk. - boot_disk_kms_key is required when - enable_confidential_storage is true. This is only available - for private preview. + Optional. Reserved for future use. + secondary_boot_disks (MutableSequence[google.cloud.container_v1beta1.types.SecondaryBootDisk]): + List of secondary boot disks attached to the + nodes. """ machine_type: str = proto.Field( @@ -906,6 +907,11 @@ class NodeConfig(proto.Message): proto.BOOL, number=46, ) + secondary_boot_disks: MutableSequence["SecondaryBootDisk"] = proto.RepeatedField( + proto.MESSAGE, + number=48, + message="SecondaryBootDisk", + ) class AdvancedMachineFeatures(proto.Message): @@ -5142,6 +5148,9 @@ class UpdateNodePoolRequest(proto.Message): Engine firewalls using Network Firewall Policies. Existing tags will be replaced with new values. + queued_provisioning (google.cloud.container_v1beta1.types.NodePool.QueuedProvisioning): + Specifies the configuration of queued + provisioning. """ project_id: str = proto.Field( @@ -5272,6 +5281,11 @@ class UpdateNodePoolRequest(proto.Message): number=39, message="ResourceManagerTags", ) + queued_provisioning: "NodePool.QueuedProvisioning" = proto.Field( + proto.MESSAGE, + number=42, + message="NodePool.QueuedProvisioning", + ) class SetNodePoolAutoscalingRequest(proto.Message): @@ -10372,4 +10386,41 @@ class ClusterTier(proto.Enum): ) +class SecondaryBootDisk(proto.Message): + r"""SecondaryBootDisk represents a persistent disk attached to a + node with special configurations based on its mode. + + Attributes: + mode (google.cloud.container_v1beta1.types.SecondaryBootDisk.Mode): + Disk mode (container image cache, etc.) + disk_image (str): + Fully-qualified resource ID for an existing + disk image. + """ + + class Mode(proto.Enum): + r"""Mode specifies how the secondary boot disk will be used. + This triggers mode-specified logic in the control plane. + + Values: + MODE_UNSPECIFIED (0): + MODE_UNSPECIFIED is when mode is not set. + CONTAINER_IMAGE_CACHE (1): + CONTAINER_IMAGE_CACHE is for using the secondary boot disk + as a container image cache. + """ + MODE_UNSPECIFIED = 0 + CONTAINER_IMAGE_CACHE = 1 + + mode: Mode = proto.Field( + proto.ENUM, + number=1, + enum=Mode, + ) + disk_image: str = proto.Field( + proto.STRING, + number=2, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-container/samples/generated_samples/snippet_metadata_google.container.v1.json b/packages/google-cloud-container/samples/generated_samples/snippet_metadata_google.container.v1.json index 27eca6e11754..6477c8ef29b8 100644 --- a/packages/google-cloud-container/samples/generated_samples/snippet_metadata_google.container.v1.json +++ b/packages/google-cloud-container/samples/generated_samples/snippet_metadata_google.container.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-container", - "version": "2.41.0" + "version": "2.42.0" }, "snippets": [ { diff --git a/packages/google-cloud-container/samples/generated_samples/snippet_metadata_google.container.v1beta1.json b/packages/google-cloud-container/samples/generated_samples/snippet_metadata_google.container.v1beta1.json index 1aaec109d1c2..f788bb23eafa 100644 --- a/packages/google-cloud-container/samples/generated_samples/snippet_metadata_google.container.v1beta1.json +++ b/packages/google-cloud-container/samples/generated_samples/snippet_metadata_google.container.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-container", - "version": "2.41.0" + "version": "2.42.0" }, "snippets": [ { diff --git a/packages/google-cloud-container/scripts/fixup_container_v1beta1_keywords.py b/packages/google-cloud-container/scripts/fixup_container_v1beta1_keywords.py index 7d38a32fd2b4..f31d4ac3b9a7 100644 --- a/packages/google-cloud-container/scripts/fixup_container_v1beta1_keywords.py +++ b/packages/google-cloud-container/scripts/fixup_container_v1beta1_keywords.py @@ -73,7 +73,7 @@ class containerCallTransformer(cst.CSTTransformer): 'start_ip_rotation': ('project_id', 'zone', 'cluster_id', 'name', 'rotate_credentials', ), 'update_cluster': ('project_id', 'zone', 'cluster_id', 'update', 'name', ), 'update_master': ('project_id', 'zone', 'cluster_id', 'master_version', 'name', ), - 'update_node_pool': ('project_id', 'zone', 'cluster_id', 'node_pool_id', 'node_version', 'image_type', 'locations', 'workload_metadata_config', 'name', 'upgrade_settings', 'tags', 'taints', 'labels', 'linux_node_config', 'kubelet_config', 'node_network_config', 'gcfs_config', 'confidential_nodes', 'gvnic', 'etag', 'fast_socket', 'logging_config', 'resource_labels', 'windows_node_config', 'machine_type', 'disk_type', 'disk_size_gb', 'resource_manager_tags', ), + 'update_node_pool': ('project_id', 'zone', 'cluster_id', 'node_pool_id', 'node_version', 'image_type', 'locations', 'workload_metadata_config', 'name', 'upgrade_settings', 'tags', 'taints', 'labels', 'linux_node_config', 'kubelet_config', 'node_network_config', 'gcfs_config', 'confidential_nodes', 'gvnic', 'etag', 'fast_socket', 'logging_config', 'resource_labels', 'windows_node_config', 'machine_type', 'disk_type', 'disk_size_gb', 'resource_manager_tags', 'queued_provisioning', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: diff --git a/packages/google-cloud-container/setup.py b/packages/google-cloud-container/setup.py index bdc1d1c88181..a7fa778712dc 100644 --- a/packages/google-cloud-container/setup.py +++ b/packages/google-cloud-container/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-containeranalysis/CHANGELOG.md b/packages/google-cloud-containeranalysis/CHANGELOG.md index 1516cabb1d66..196cea5bcf92 100644 --- a/packages/google-cloud-containeranalysis/CHANGELOG.md +++ b/packages/google-cloud-containeranalysis/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [2.14.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-containeranalysis-v2.14.2...google-cloud-containeranalysis-v2.14.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [2.14.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-containeranalysis-v2.14.1...google-cloud-containeranalysis-v2.14.2) (2024-02-22) diff --git a/packages/google-cloud-containeranalysis/google/cloud/devtools/containeranalysis/gapic_version.py b/packages/google-cloud-containeranalysis/google/cloud/devtools/containeranalysis/gapic_version.py index e00709b42b8e..6440b3563e45 100644 --- a/packages/google-cloud-containeranalysis/google/cloud/devtools/containeranalysis/gapic_version.py +++ b/packages/google-cloud-containeranalysis/google/cloud/devtools/containeranalysis/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.14.2" # {x-release-please-version} +__version__ = "2.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-containeranalysis/google/cloud/devtools/containeranalysis_v1/gapic_version.py b/packages/google-cloud-containeranalysis/google/cloud/devtools/containeranalysis_v1/gapic_version.py index e00709b42b8e..6440b3563e45 100644 --- a/packages/google-cloud-containeranalysis/google/cloud/devtools/containeranalysis_v1/gapic_version.py +++ b/packages/google-cloud-containeranalysis/google/cloud/devtools/containeranalysis_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.2" # {x-release-please-version} +__version__ = "2.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-containeranalysis/samples/generated_samples/snippet_metadata_google.devtools.containeranalysis.v1.json b/packages/google-cloud-containeranalysis/samples/generated_samples/snippet_metadata_google.devtools.containeranalysis.v1.json index 69efc747ed8d..9a53f9cec3b3 100644 --- a/packages/google-cloud-containeranalysis/samples/generated_samples/snippet_metadata_google.devtools.containeranalysis.v1.json +++ b/packages/google-cloud-containeranalysis/samples/generated_samples/snippet_metadata_google.devtools.containeranalysis.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-containeranalysis", - "version": "2.14.2" + "version": "2.14.3" }, "snippets": [ { diff --git a/packages/google-cloud-containeranalysis/setup.py b/packages/google-cloud-containeranalysis/setup.py index c51706e03fa1..e97b9684c512 100644 --- a/packages/google-cloud-containeranalysis/setup.py +++ b/packages/google-cloud-containeranalysis/setup.py @@ -44,7 +44,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "grafeas >=1.4.1, <2.0dev", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", diff --git a/packages/google-cloud-contentwarehouse/CHANGELOG.md b/packages/google-cloud-contentwarehouse/CHANGELOG.md index 13c9a2e4096b..0fbd86f375b5 100644 --- a/packages/google-cloud-contentwarehouse/CHANGELOG.md +++ b/packages/google-cloud-contentwarehouse/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.7.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-contentwarehouse-v0.7.6...google-cloud-contentwarehouse-v0.7.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [0.7.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-contentwarehouse-v0.7.5...google-cloud-contentwarehouse-v0.7.6) (2024-02-22) 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 8cdf0f71dd60..85aff6a4df40 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.6" # {x-release-please-version} +__version__ = "0.7.7" # {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 8cdf0f71dd60..85aff6a4df40 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.6" # {x-release-please-version} +__version__ = "0.7.7" # {x-release-please-version} 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 27a4c5b3a4c0..e0bfe863abf5 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.6" + "version": "0.7.7" }, "snippets": [ { diff --git a/packages/google-cloud-contentwarehouse/setup.py b/packages/google-cloud-contentwarehouse/setup.py index d9db6e3a0346..8382bd78f7f9 100644 --- a/packages/google-cloud-contentwarehouse/setup.py +++ b/packages/google-cloud-contentwarehouse/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=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", diff --git a/packages/google-cloud-data-fusion/CHANGELOG.md b/packages/google-cloud-data-fusion/CHANGELOG.md index cb380670a52c..3fc7c7b4913e 100644 --- a/packages/google-cloud-data-fusion/CHANGELOG.md +++ b/packages/google-cloud-data-fusion/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.10.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-data-fusion-v1.10.2...google-cloud-data-fusion-v1.10.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [1.10.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-data-fusion-v1.10.1...google-cloud-data-fusion-v1.10.2) (2024-02-22) 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 7a033a50e6cd..d74c07c1961e 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.10.2" # {x-release-please-version} +__version__ = "1.10.3" # {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 7a033a50e6cd..d74c07c1961e 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.10.2" # {x-release-please-version} +__version__ = "1.10.3" # {x-release-please-version} 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 f19a7b2f3c0d..05212202bc5d 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.10.2" + "version": "1.10.3" }, "snippets": [ { diff --git a/packages/google-cloud-data-fusion/setup.py b/packages/google-cloud-data-fusion/setup.py index cd734360eca0..08c05f7b0bca 100644 --- a/packages/google-cloud-data-fusion/setup.py +++ b/packages/google-cloud-data-fusion/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-data-qna/CHANGELOG.md b/packages/google-cloud-data-qna/CHANGELOG.md index 05f5afb59978..630f55eda499 100644 --- a/packages/google-cloud-data-qna/CHANGELOG.md +++ b/packages/google-cloud-data-qna/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.10.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-data-qna-v0.10.8...google-cloud-data-qna-v0.10.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [0.10.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-data-qna-v0.10.7...google-cloud-data-qna-v0.10.8) (2024-02-22) 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 8986f58b4e1e..4d3143c8cc8e 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.8" # {x-release-please-version} +__version__ = "0.10.9" # {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 8986f58b4e1e..4d3143c8cc8e 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.8" # {x-release-please-version} +__version__ = "0.10.9" # {x-release-please-version} 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 f062029d4ab2..99bacdc4dd23 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.8" + "version": "0.10.9" }, "snippets": [ { diff --git a/packages/google-cloud-data-qna/setup.py b/packages/google-cloud-data-qna/setup.py index fe018c918cdc..a64237dd94c9 100644 --- a/packages/google-cloud-data-qna/setup.py +++ b/packages/google-cloud-data-qna/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-datacatalog-lineage/CHANGELOG.md b/packages/google-cloud-datacatalog-lineage/CHANGELOG.md index a399f89e1803..e0fbae522e02 100644 --- a/packages/google-cloud-datacatalog-lineage/CHANGELOG.md +++ b/packages/google-cloud-datacatalog-lineage/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.3.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-datacatalog-lineage-v0.3.5...google-cloud-datacatalog-lineage-v0.3.6) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [0.3.5](https://github.com/googleapis/google-cloud-python/compare/google-cloud-datacatalog-lineage-v0.3.4...google-cloud-datacatalog-lineage-v0.3.5) (2024-02-22) 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 288d10b11145..dca6dc837e67 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.5" # {x-release-please-version} +__version__ = "0.3.6" # {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 288d10b11145..dca6dc837e67 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.5" # {x-release-please-version} +__version__ = "0.3.6" # {x-release-please-version} 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 d799aa4de5ab..c64388dd61ca 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.5" + "version": "0.3.6" }, "snippets": [ { diff --git a/packages/google-cloud-datacatalog-lineage/setup.py b/packages/google-cloud-datacatalog-lineage/setup.py index 47ef9e3db554..f84e99561f29 100644 --- a/packages/google-cloud-datacatalog-lineage/setup.py +++ b/packages/google-cloud-datacatalog-lineage/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-datacatalog/CHANGELOG.md b/packages/google-cloud-datacatalog/CHANGELOG.md index 854b83bbb5a5..803cddc72e4b 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.18.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-datacatalog-v3.18.2...google-cloud-datacatalog-v3.18.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [3.18.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-datacatalog-v3.18.1...google-cloud-datacatalog-v3.18.2) (2024-02-22) 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 662f8643dab7..eab7fce6bdae 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.18.2" # {x-release-please-version} +__version__ = "3.18.3" # {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 662f8643dab7..eab7fce6bdae 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.18.2" # {x-release-please-version} +__version__ = "3.18.3" # {x-release-please-version} 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 662f8643dab7..eab7fce6bdae 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.18.2" # {x-release-please-version} +__version__ = "3.18.3" # {x-release-please-version} 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 2016800fe7c9..458ebdb8eeda 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.18.2" + "version": "3.18.3" }, "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 76bcc58b38d4..a9c89eee8b87 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.18.2" + "version": "3.18.3" }, "snippets": [ { diff --git a/packages/google-cloud-datacatalog/setup.py b/packages/google-cloud-datacatalog/setup.py index f15611c45dc6..4cb23b5235e9 100644 --- a/packages/google-cloud-datacatalog/setup.py +++ b/packages/google-cloud-datacatalog/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-dataflow-client/CHANGELOG.md b/packages/google-cloud-dataflow-client/CHANGELOG.md index 4a0a1af598d6..d7f8b2e78ceb 100644 --- a/packages/google-cloud-dataflow-client/CHANGELOG.md +++ b/packages/google-cloud-dataflow-client/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.8.10](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dataflow-client-v0.8.9...google-cloud-dataflow-client-v0.8.10) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [0.8.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dataflow-client-v0.8.8...google-cloud-dataflow-client-v0.8.9) (2024-02-22) diff --git a/packages/google-cloud-dataflow-client/google/cloud/dataflow/gapic_version.py b/packages/google-cloud-dataflow-client/google/cloud/dataflow/gapic_version.py index f0250f692033..e03781aedee3 100644 --- a/packages/google-cloud-dataflow-client/google/cloud/dataflow/gapic_version.py +++ b/packages/google-cloud-dataflow-client/google/cloud/dataflow/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.8.9" # {x-release-please-version} +__version__ = "0.8.10" # {x-release-please-version} diff --git a/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/gapic_version.py b/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/gapic_version.py index f0250f692033..e03781aedee3 100644 --- a/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/gapic_version.py +++ b/packages/google-cloud-dataflow-client/google/cloud/dataflow_v1beta3/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.8.9" # {x-release-please-version} +__version__ = "0.8.10" # {x-release-please-version} diff --git a/packages/google-cloud-dataflow-client/samples/generated_samples/snippet_metadata_google.dataflow.v1beta3.json b/packages/google-cloud-dataflow-client/samples/generated_samples/snippet_metadata_google.dataflow.v1beta3.json index 6df0638452e9..56dd987e134f 100644 --- a/packages/google-cloud-dataflow-client/samples/generated_samples/snippet_metadata_google.dataflow.v1beta3.json +++ b/packages/google-cloud-dataflow-client/samples/generated_samples/snippet_metadata_google.dataflow.v1beta3.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-dataflow-client", - "version": "0.8.9" + "version": "0.8.10" }, "snippets": [ { diff --git a/packages/google-cloud-dataflow-client/setup.py b/packages/google-cloud-dataflow-client/setup.py index c7418852bad6..7e44b4f64cd1 100644 --- a/packages/google-cloud-dataflow-client/setup.py +++ b/packages/google-cloud-dataflow-client/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-dataform/CHANGELOG.md b/packages/google-cloud-dataform/CHANGELOG.md index dd3e69ca5e5b..9b332919771e 100644 --- a/packages/google-cloud-dataform/CHANGELOG.md +++ b/packages/google-cloud-dataform/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.5.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dataform-v0.5.8...google-cloud-dataform-v0.5.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [0.5.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dataform-v0.5.7...google-cloud-dataform-v0.5.8) (2024-02-22) 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 09f1bfa9ad82..f4186fc1a151 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.8" # {x-release-please-version} +__version__ = "0.5.9" # {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 09f1bfa9ad82..f4186fc1a151 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.8" # {x-release-please-version} +__version__ = "0.5.9" # {x-release-please-version} 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 6474c382315a..f6127f1770e8 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.8" + "version": "0.5.9" }, "snippets": [ { diff --git a/packages/google-cloud-dataform/setup.py b/packages/google-cloud-dataform/setup.py index bb98c6b06be9..13f49334f95c 100644 --- a/packages/google-cloud-dataform/setup.py +++ b/packages/google-cloud-dataform/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-datalabeling/CHANGELOG.md b/packages/google-cloud-datalabeling/CHANGELOG.md index 28c1875ecbd4..e2368679cf1f 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.10.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-datalabeling-v1.10.2...google-cloud-datalabeling-v1.10.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [1.10.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-datalabeling-v1.10.1...google-cloud-datalabeling-v1.10.2) (2024-02-22) 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 7a033a50e6cd..d74c07c1961e 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.10.2" # {x-release-please-version} +__version__ = "1.10.3" # {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 7a033a50e6cd..d74c07c1961e 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.10.2" # {x-release-please-version} +__version__ = "1.10.3" # {x-release-please-version} 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 6deb8dd27993..d95b4dd0566d 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.10.2" + "version": "1.10.3" }, "snippets": [ { diff --git a/packages/google-cloud-datalabeling/setup.py b/packages/google-cloud-datalabeling/setup.py index e5b4d02a6c1b..60131ceb7efe 100644 --- a/packages/google-cloud-datalabeling/setup.py +++ b/packages/google-cloud-datalabeling/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-dataplex/CHANGELOG.md b/packages/google-cloud-dataplex/CHANGELOG.md index 9b856c100fb2..8740ad1c7461 100644 --- a/packages/google-cloud-dataplex/CHANGELOG.md +++ b/packages/google-cloud-dataplex/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.12.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dataplex-v1.12.2...google-cloud-dataplex-v1.12.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [1.12.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dataplex-v1.12.1...google-cloud-dataplex-v1.12.2) (2024-02-22) 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 394a70bae1a3..12049b60eb6c 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__ = "1.12.2" # {x-release-please-version} +__version__ = "1.12.3" # {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 394a70bae1a3..12049b60eb6c 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__ = "1.12.2" # {x-release-please-version} +__version__ = "1.12.3" # {x-release-please-version} 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 bf8a61d8c865..98df00d7e4c8 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": "1.12.2" + "version": "1.12.3" }, "snippets": [ { diff --git a/packages/google-cloud-dataplex/setup.py b/packages/google-cloud-dataplex/setup.py index f5896626b31a..98028f00798f 100644 --- a/packages/google-cloud-dataplex/setup.py +++ b/packages/google-cloud-dataplex/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-dataproc-metastore/CHANGELOG.md b/packages/google-cloud-dataproc-metastore/CHANGELOG.md index e68864075620..ca625fe5409b 100644 --- a/packages/google-cloud-dataproc-metastore/CHANGELOG.md +++ b/packages/google-cloud-dataproc-metastore/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.15.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dataproc-metastore-v1.15.2...google-cloud-dataproc-metastore-v1.15.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [1.15.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dataproc-metastore-v1.15.1...google-cloud-dataproc-metastore-v1.15.2) (2024-02-22) diff --git a/packages/google-cloud-dataproc-metastore/google/cloud/metastore/gapic_version.py b/packages/google-cloud-dataproc-metastore/google/cloud/metastore/gapic_version.py index 2b083704400c..7f190df1d2bb 100644 --- a/packages/google-cloud-dataproc-metastore/google/cloud/metastore/gapic_version.py +++ b/packages/google-cloud-dataproc-metastore/google/cloud/metastore/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.15.2" # {x-release-please-version} +__version__ = "1.15.3" # {x-release-please-version} diff --git a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1/gapic_version.py b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1/gapic_version.py index 2b083704400c..7f190df1d2bb 100644 --- a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1/gapic_version.py +++ b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_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.2" # {x-release-please-version} +__version__ = "1.15.3" # {x-release-please-version} diff --git a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1alpha/gapic_version.py b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1alpha/gapic_version.py index 2b083704400c..7f190df1d2bb 100644 --- a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1alpha/gapic_version.py +++ b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.15.2" # {x-release-please-version} +__version__ = "1.15.3" # {x-release-please-version} diff --git a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1beta/gapic_version.py b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1beta/gapic_version.py index 2b083704400c..7f190df1d2bb 100644 --- a/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1beta/gapic_version.py +++ b/packages/google-cloud-dataproc-metastore/google/cloud/metastore_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.15.2" # {x-release-please-version} +__version__ = "1.15.3" # {x-release-please-version} diff --git a/packages/google-cloud-dataproc-metastore/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1.json b/packages/google-cloud-dataproc-metastore/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1.json index bfa4a4dfe198..ae902b327878 100644 --- a/packages/google-cloud-dataproc-metastore/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1.json +++ b/packages/google-cloud-dataproc-metastore/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-dataproc-metastore", - "version": "1.15.2" + "version": "1.15.3" }, "snippets": [ { diff --git a/packages/google-cloud-dataproc-metastore/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1alpha.json b/packages/google-cloud-dataproc-metastore/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1alpha.json index ea6583ca7496..0f7ac9037f7e 100644 --- a/packages/google-cloud-dataproc-metastore/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1alpha.json +++ b/packages/google-cloud-dataproc-metastore/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-dataproc-metastore", - "version": "1.15.2" + "version": "1.15.3" }, "snippets": [ { diff --git a/packages/google-cloud-dataproc-metastore/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1beta.json b/packages/google-cloud-dataproc-metastore/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1beta.json index f2a8e1e334d6..14aa3a9301ff 100644 --- a/packages/google-cloud-dataproc-metastore/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1beta.json +++ b/packages/google-cloud-dataproc-metastore/samples/generated_samples/snippet_metadata_google.cloud.metastore.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-dataproc-metastore", - "version": "1.15.2" + "version": "1.15.3" }, "snippets": [ { diff --git a/packages/google-cloud-dataproc-metastore/setup.py b/packages/google-cloud-dataproc-metastore/setup.py index 0f0973d18e5a..cfa456242043 100644 --- a/packages/google-cloud-dataproc-metastore/setup.py +++ b/packages/google-cloud-dataproc-metastore/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-dataproc/CHANGELOG.md b/packages/google-cloud-dataproc/CHANGELOG.md index 05e6995440d2..2103594b2890 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.9.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dataproc-v5.9.2...google-cloud-dataproc-v5.9.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12383](https://github.com/googleapis/google-cloud-python/issues/12383)) ([305f43f](https://github.com/googleapis/google-cloud-python/commit/305f43f7d6293e3316248f421fdc19c5d8405c21)) + ## [5.9.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dataproc-v5.9.1...google-cloud-dataproc-v5.9.2) (2024-02-22) 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 5d79297022ca..6a714e6ae354 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.9.2" # {x-release-please-version} +__version__ = "5.9.3" # {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 5d79297022ca..6a714e6ae354 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.9.2" # {x-release-please-version} +__version__ = "5.9.3" # {x-release-please-version} 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 5b39b0c2df6f..52c7df3b3f88 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.9.2" + "version": "5.9.3" }, "snippets": [ { diff --git a/packages/google-cloud-dataproc/setup.py b/packages/google-cloud-dataproc/setup.py index b9b054b3dbfa..074638de0c70 100644 --- a/packages/google-cloud-dataproc/setup.py +++ b/packages/google-cloud-dataproc/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-datastream/CHANGELOG.md b/packages/google-cloud-datastream/CHANGELOG.md index ed571c673234..aea47f9d9b35 100644 --- a/packages/google-cloud-datastream/CHANGELOG.md +++ b/packages/google-cloud-datastream/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.9.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-datastream-v1.9.2...google-cloud-datastream-v1.9.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [1.9.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-datastream-v1.9.1...google-cloud-datastream-v1.9.2) (2024-02-22) 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 f14078b6f555..ec42a8e289c4 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.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {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 f14078b6f555..ec42a8e289c4 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.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} 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 f14078b6f555..ec42a8e289c4 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.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} 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 e1cdef01d78b..edad19376a85 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.9.2" + "version": "1.9.3" }, "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 089de0e7d063..f6a87ccb182d 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.9.2" + "version": "1.9.3" }, "snippets": [ { diff --git a/packages/google-cloud-datastream/setup.py b/packages/google-cloud-datastream/setup.py index a3e77a3b9d86..9be59b9eac4a 100644 --- a/packages/google-cloud-datastream/setup.py +++ b/packages/google-cloud-datastream/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-deploy/CHANGELOG.md b/packages/google-cloud-deploy/CHANGELOG.md index f7e06a4d321c..b3546f84b012 100644 --- a/packages/google-cloud-deploy/CHANGELOG.md +++ b/packages/google-cloud-deploy/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.17.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-deploy-v1.17.2...google-cloud-deploy-v1.17.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [1.17.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-deploy-v1.17.1...google-cloud-deploy-v1.17.2) (2024-02-22) 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 1e0921955b0c..3639317ee4f0 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__ = "1.17.2" # {x-release-please-version} +__version__ = "1.17.3" # {x-release-please-version} 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 1e0921955b0c..3639317ee4f0 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__ = "1.17.2" # {x-release-please-version} +__version__ = "1.17.3" # {x-release-please-version} 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 fc9a4bb47342..aa51daa606b6 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": "1.17.2" + "version": "1.17.3" }, "snippets": [ { diff --git a/packages/google-cloud-deploy/setup.py b/packages/google-cloud-deploy/setup.py index cc1f5e36c719..de93b87e0951 100644 --- a/packages/google-cloud-deploy/setup.py +++ b/packages/google-cloud-deploy/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-dialogflow-cx/CHANGELOG.md b/packages/google-cloud-dialogflow-cx/CHANGELOG.md index 09d9ca17dc4d..d421da19df27 100644 --- a/packages/google-cloud-dialogflow-cx/CHANGELOG.md +++ b/packages/google-cloud-dialogflow-cx/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.32.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dialogflow-cx-v1.32.0...google-cloud-dialogflow-cx-v1.32.1) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12390](https://github.com/googleapis/google-cloud-python/issues/12390)) ([25c291a](https://github.com/googleapis/google-cloud-python/commit/25c291afa9facc72f4af80b9c2721efe24b02953)) + ## [1.32.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dialogflow-cx-v1.31.1...google-cloud-dialogflow-cx-v1.32.0) (2024-02-22) diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx/gapic_version.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx/gapic_version.py index 1724106145aa..3302f1aee5b6 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx/gapic_version.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.32.0" # {x-release-please-version} +__version__ = "1.32.1" # {x-release-please-version} diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/gapic_version.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/gapic_version.py index 1724106145aa..3302f1aee5b6 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/gapic_version.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.32.0" # {x-release-please-version} +__version__ = "1.32.1" # {x-release-please-version} diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/gapic_version.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/gapic_version.py index 1724106145aa..3302f1aee5b6 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/gapic_version.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.32.0" # {x-release-please-version} +__version__ = "1.32.1" # {x-release-please-version} diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.cx.v3.json b/packages/google-cloud-dialogflow-cx/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.cx.v3.json index 402a8ceaf2f8..bd022d69eab4 100644 --- a/packages/google-cloud-dialogflow-cx/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.cx.v3.json +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.cx.v3.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-dialogflow-cx", - "version": "1.32.0" + "version": "1.32.1" }, "snippets": [ { diff --git a/packages/google-cloud-dialogflow-cx/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.cx.v3beta1.json b/packages/google-cloud-dialogflow-cx/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.cx.v3beta1.json index 930f6d76c947..01011fa02b83 100644 --- a/packages/google-cloud-dialogflow-cx/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.cx.v3beta1.json +++ b/packages/google-cloud-dialogflow-cx/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.cx.v3beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-dialogflow-cx", - "version": "1.32.0" + "version": "1.32.1" }, "snippets": [ { diff --git a/packages/google-cloud-dialogflow-cx/setup.py b/packages/google-cloud-dialogflow-cx/setup.py index 521fb029e522..0939864e7c66 100644 --- a/packages/google-cloud-dialogflow-cx/setup.py +++ b/packages/google-cloud-dialogflow-cx/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-dialogflow/CHANGELOG.md b/packages/google-cloud-dialogflow/CHANGELOG.md index c1045d7de86d..f828b742b747 100644 --- a/packages/google-cloud-dialogflow/CHANGELOG.md +++ b/packages/google-cloud-dialogflow/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/dialogflow/#history +## [2.28.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dialogflow-v2.28.2...google-cloud-dialogflow-v2.28.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [2.28.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dialogflow-v2.28.1...google-cloud-dialogflow-v2.28.2) (2024-02-22) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow/gapic_version.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow/gapic_version.py index d934b18057d6..ce9437f965e8 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow/gapic_version.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.28.2" # {x-release-please-version} +__version__ = "2.28.3" # {x-release-please-version} diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/gapic_version.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/gapic_version.py index d934b18057d6..ce9437f965e8 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/gapic_version.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.28.2" # {x-release-please-version} +__version__ = "2.28.3" # {x-release-please-version} diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/gapic_version.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/gapic_version.py index d934b18057d6..ce9437f965e8 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/gapic_version.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.28.2" # {x-release-please-version} +__version__ = "2.28.3" # {x-release-please-version} diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2.json b/packages/google-cloud-dialogflow/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2.json index f4f767deebd8..3e25c9fed4fb 100644 --- a/packages/google-cloud-dialogflow/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2.json +++ b/packages/google-cloud-dialogflow/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-dialogflow", - "version": "2.28.2" + "version": "2.28.3" }, "snippets": [ { diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2beta1.json b/packages/google-cloud-dialogflow/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2beta1.json index ceccdbe15ebb..50ea923075f4 100644 --- a/packages/google-cloud-dialogflow/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2beta1.json +++ b/packages/google-cloud-dialogflow/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-dialogflow", - "version": "2.28.2" + "version": "2.28.3" }, "snippets": [ { diff --git a/packages/google-cloud-dialogflow/setup.py b/packages/google-cloud-dialogflow/setup.py index b128e4feccb5..9e6fdf806d7e 100644 --- a/packages/google-cloud-dialogflow/setup.py +++ b/packages/google-cloud-dialogflow/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-discoveryengine/CHANGELOG.md b/packages/google-cloud-discoveryengine/CHANGELOG.md index 6ecc5b97e6e6..aad4449aabb3 100644 --- a/packages/google-cloud-discoveryengine/CHANGELOG.md +++ b/packages/google-cloud-discoveryengine/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.11.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-discoveryengine-v0.11.8...google-cloud-discoveryengine-v0.11.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [0.11.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-discoveryengine-v0.11.7...google-cloud-discoveryengine-v0.11.8) (2024-02-22) 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 651274e67675..456019f7dbab 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.11.8" # {x-release-please-version} +__version__ = "0.11.9" # {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 651274e67675..456019f7dbab 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.11.8" # {x-release-please-version} +__version__ = "0.11.9" # {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 651274e67675..456019f7dbab 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.11.8" # {x-release-please-version} +__version__ = "0.11.9" # {x-release-please-version} 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 651274e67675..456019f7dbab 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.11.8" # {x-release-please-version} +__version__ = "0.11.9" # {x-release-please-version} 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 383294d8d514..97ccc46cdf0c 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.11.8" + "version": "0.11.9" }, "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 25bdc80985b9..4fb7de7fc27d 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.11.8" + "version": "0.11.9" }, "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 759c85432ff5..7aa8433cc886 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,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-discoveryengine", - "version": "0.11.8" + "version": "0.11.9" }, "snippets": [ { diff --git a/packages/google-cloud-discoveryengine/setup.py b/packages/google-cloud-discoveryengine/setup.py index e586b5f75435..f73b6a95badc 100644 --- a/packages/google-cloud-discoveryengine/setup.py +++ b/packages/google-cloud-discoveryengine/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-dlp/CHANGELOG.md b/packages/google-cloud-dlp/CHANGELOG.md index 9c28fea30b33..dbdeb6c31b8c 100644 --- a/packages/google-cloud-dlp/CHANGELOG.md +++ b/packages/google-cloud-dlp/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-dlp/#history +## [3.15.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dlp-v3.15.2...google-cloud-dlp-v3.15.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [3.15.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dlp-v3.15.1...google-cloud-dlp-v3.15.2) (2024-02-22) diff --git a/packages/google-cloud-dlp/google/cloud/dlp/gapic_version.py b/packages/google-cloud-dlp/google/cloud/dlp/gapic_version.py index dcf8378be674..8a4674fe081d 100644 --- a/packages/google-cloud-dlp/google/cloud/dlp/gapic_version.py +++ b/packages/google-cloud-dlp/google/cloud/dlp/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.15.2" # {x-release-please-version} +__version__ = "3.15.3" # {x-release-please-version} diff --git a/packages/google-cloud-dlp/google/cloud/dlp_v2/gapic_version.py b/packages/google-cloud-dlp/google/cloud/dlp_v2/gapic_version.py index dcf8378be674..8a4674fe081d 100644 --- a/packages/google-cloud-dlp/google/cloud/dlp_v2/gapic_version.py +++ b/packages/google-cloud-dlp/google/cloud/dlp_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.15.2" # {x-release-please-version} +__version__ = "3.15.3" # {x-release-please-version} diff --git a/packages/google-cloud-dlp/samples/generated_samples/snippet_metadata_google.privacy.dlp.v2.json b/packages/google-cloud-dlp/samples/generated_samples/snippet_metadata_google.privacy.dlp.v2.json index 7701f5d3f257..89e2a73246b1 100644 --- a/packages/google-cloud-dlp/samples/generated_samples/snippet_metadata_google.privacy.dlp.v2.json +++ b/packages/google-cloud-dlp/samples/generated_samples/snippet_metadata_google.privacy.dlp.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-dlp", - "version": "3.15.2" + "version": "3.15.3" }, "snippets": [ { diff --git a/packages/google-cloud-dlp/setup.py b/packages/google-cloud-dlp/setup.py index eeb3be3eefba..9251055a4552 100644 --- a/packages/google-cloud-dlp/setup.py +++ b/packages/google-cloud-dlp/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-dms/CHANGELOG.md b/packages/google-cloud-dms/CHANGELOG.md index d5cc72878c76..977e8a7e92f1 100644 --- a/packages/google-cloud-dms/CHANGELOG.md +++ b/packages/google-cloud-dms/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.9.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dms-v1.9.2...google-cloud-dms-v1.9.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [1.9.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-dms-v1.9.1...google-cloud-dms-v1.9.2) (2024-02-22) 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 f14078b6f555..ec42a8e289c4 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.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {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 f14078b6f555..ec42a8e289c4 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.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} 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 2b1b81fb07b8..66be194069d9 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.9.2" + "version": "1.9.3" }, "snippets": [ { diff --git a/packages/google-cloud-dms/setup.py b/packages/google-cloud-dms/setup.py index 236478b01922..1c04517e5614 100644 --- a/packages/google-cloud-dms/setup.py +++ b/packages/google-cloud-dms/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-documentai/CHANGELOG.md b/packages/google-cloud-documentai/CHANGELOG.md index a98c3ae1904e..c3cfa1f21588 100644 --- a/packages/google-cloud-documentai/CHANGELOG.md +++ b/packages/google-cloud-documentai/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [2.24.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-documentai-v2.24.0...google-cloud-documentai-v2.24.1) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [2.24.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-documentai-v2.23.0...google-cloud-documentai-v2.24.0) (2024-02-22) diff --git a/packages/google-cloud-documentai/google/cloud/documentai/gapic_version.py b/packages/google-cloud-documentai/google/cloud/documentai/gapic_version.py index ff6eaf3d5023..720a47bdbdeb 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai/gapic_version.py +++ b/packages/google-cloud-documentai/google/cloud/documentai/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.24.0" # {x-release-please-version} +__version__ = "2.24.1" # {x-release-please-version} diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1/gapic_version.py b/packages/google-cloud-documentai/google/cloud/documentai_v1/gapic_version.py index ff6eaf3d5023..720a47bdbdeb 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1/gapic_version.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.24.0" # {x-release-please-version} +__version__ = "2.24.1" # {x-release-please-version} diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta2/gapic_version.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta2/gapic_version.py index ff6eaf3d5023..720a47bdbdeb 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta2/gapic_version.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.24.0" # {x-release-please-version} +__version__ = "2.24.1" # {x-release-please-version} diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/gapic_version.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/gapic_version.py index ff6eaf3d5023..720a47bdbdeb 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/gapic_version.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.24.0" # {x-release-please-version} +__version__ = "2.24.1" # {x-release-please-version} diff --git a/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json b/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json index d9ffc298d80a..f2f229307252 100644 --- a/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json +++ b/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-documentai", - "version": "2.24.0" + "version": "2.24.1" }, "snippets": [ { diff --git a/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json b/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json index 374dba6e40b4..23f35397a2ef 100644 --- a/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json +++ b/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-documentai", - "version": "2.24.0" + "version": "2.24.1" }, "snippets": [ { diff --git a/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json b/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json index ffc2ee31a6e0..6cfea814e770 100644 --- a/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json +++ b/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-documentai", - "version": "2.24.0" + "version": "2.24.1" }, "snippets": [ { diff --git a/packages/google-cloud-documentai/setup.py b/packages/google-cloud-documentai/setup.py index 5802dd1125be..3efe98c4216f 100644 --- a/packages/google-cloud-documentai/setup.py +++ b/packages/google-cloud-documentai/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-domains/CHANGELOG.md b/packages/google-cloud-domains/CHANGELOG.md index 4aad45981565..87450eb07711 100644 --- a/packages/google-cloud-domains/CHANGELOG.md +++ b/packages/google-cloud-domains/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.7.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-domains-v1.7.2...google-cloud-domains-v1.7.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [1.7.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-domains-v1.7.1...google-cloud-domains-v1.7.2) (2024-02-22) diff --git a/packages/google-cloud-domains/google/cloud/domains/gapic_version.py b/packages/google-cloud-domains/google/cloud/domains/gapic_version.py index a71edaad33ab..84f198c2d605 100644 --- a/packages/google-cloud-domains/google/cloud/domains/gapic_version.py +++ b/packages/google-cloud-domains/google/cloud/domains/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.7.2" # {x-release-please-version} +__version__ = "1.7.3" # {x-release-please-version} diff --git a/packages/google-cloud-domains/google/cloud/domains_v1/gapic_version.py b/packages/google-cloud-domains/google/cloud/domains_v1/gapic_version.py index a71edaad33ab..84f198c2d605 100644 --- a/packages/google-cloud-domains/google/cloud/domains_v1/gapic_version.py +++ b/packages/google-cloud-domains/google/cloud/domains_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.7.2" # {x-release-please-version} +__version__ = "1.7.3" # {x-release-please-version} diff --git a/packages/google-cloud-domains/google/cloud/domains_v1beta1/gapic_version.py b/packages/google-cloud-domains/google/cloud/domains_v1beta1/gapic_version.py index a71edaad33ab..84f198c2d605 100644 --- a/packages/google-cloud-domains/google/cloud/domains_v1beta1/gapic_version.py +++ b/packages/google-cloud-domains/google/cloud/domains_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.7.2" # {x-release-please-version} +__version__ = "1.7.3" # {x-release-please-version} diff --git a/packages/google-cloud-domains/samples/generated_samples/snippet_metadata_google.cloud.domains.v1.json b/packages/google-cloud-domains/samples/generated_samples/snippet_metadata_google.cloud.domains.v1.json index 088a9ab8ebd7..9b414c256353 100644 --- a/packages/google-cloud-domains/samples/generated_samples/snippet_metadata_google.cloud.domains.v1.json +++ b/packages/google-cloud-domains/samples/generated_samples/snippet_metadata_google.cloud.domains.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-domains", - "version": "1.7.2" + "version": "1.7.3" }, "snippets": [ { diff --git a/packages/google-cloud-domains/samples/generated_samples/snippet_metadata_google.cloud.domains.v1beta1.json b/packages/google-cloud-domains/samples/generated_samples/snippet_metadata_google.cloud.domains.v1beta1.json index 257b808a90df..ea33f4782545 100644 --- a/packages/google-cloud-domains/samples/generated_samples/snippet_metadata_google.cloud.domains.v1beta1.json +++ b/packages/google-cloud-domains/samples/generated_samples/snippet_metadata_google.cloud.domains.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-domains", - "version": "1.7.2" + "version": "1.7.3" }, "snippets": [ { diff --git a/packages/google-cloud-domains/setup.py b/packages/google-cloud-domains/setup.py index d13b492f3f69..df143a57900e 100644 --- a/packages/google-cloud-domains/setup.py +++ b/packages/google-cloud-domains/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-edgecontainer/CHANGELOG.md b/packages/google-cloud-edgecontainer/CHANGELOG.md index 72cb90821988..cac140329c81 100644 --- a/packages/google-cloud-edgecontainer/CHANGELOG.md +++ b/packages/google-cloud-edgecontainer/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.5.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-edgecontainer-v0.5.7...google-cloud-edgecontainer-v0.5.8) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [0.5.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-edgecontainer-v0.5.6...google-cloud-edgecontainer-v0.5.7) (2024-02-22) 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 525ae0137447..09f1bfa9ad82 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.7" # {x-release-please-version} +__version__ = "0.5.8" # {x-release-please-version} 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 525ae0137447..09f1bfa9ad82 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.7" # {x-release-please-version} +__version__ = "0.5.8" # {x-release-please-version} 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 ff2db0c8b454..76454d6fb13c 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.7" + "version": "0.5.8" }, "snippets": [ { diff --git a/packages/google-cloud-edgecontainer/setup.py b/packages/google-cloud-edgecontainer/setup.py index 3c57bb8aa09f..7b12eb216d22 100644 --- a/packages/google-cloud-edgecontainer/setup.py +++ b/packages/google-cloud-edgecontainer/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-edgenetwork/CHANGELOG.md b/packages/google-cloud-edgenetwork/CHANGELOG.md index 86187149e359..cd5be959e3b3 100644 --- a/packages/google-cloud-edgenetwork/CHANGELOG.md +++ b/packages/google-cloud-edgenetwork/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-edgenetwork-v0.1.5...google-cloud-edgenetwork-v0.1.6) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [0.1.5](https://github.com/googleapis/google-cloud-python/compare/google-cloud-edgenetwork-v0.1.4...google-cloud-edgenetwork-v0.1.5) (2024-02-22) diff --git a/packages/google-cloud-edgenetwork/google/cloud/edgenetwork/gapic_version.py b/packages/google-cloud-edgenetwork/google/cloud/edgenetwork/gapic_version.py index ae12f4dfd596..60402a4567d1 100644 --- a/packages/google-cloud-edgenetwork/google/cloud/edgenetwork/gapic_version.py +++ b/packages/google-cloud-edgenetwork/google/cloud/edgenetwork/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-edgenetwork/google/cloud/edgenetwork_v1/gapic_version.py b/packages/google-cloud-edgenetwork/google/cloud/edgenetwork_v1/gapic_version.py index ae12f4dfd596..60402a4567d1 100644 --- a/packages/google-cloud-edgenetwork/google/cloud/edgenetwork_v1/gapic_version.py +++ b/packages/google-cloud-edgenetwork/google/cloud/edgenetwork_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-edgenetwork/samples/generated_samples/snippet_metadata_google.cloud.edgenetwork.v1.json b/packages/google-cloud-edgenetwork/samples/generated_samples/snippet_metadata_google.cloud.edgenetwork.v1.json index 5c2795b4bef2..e8d378d8f624 100644 --- a/packages/google-cloud-edgenetwork/samples/generated_samples/snippet_metadata_google.cloud.edgenetwork.v1.json +++ b/packages/google-cloud-edgenetwork/samples/generated_samples/snippet_metadata_google.cloud.edgenetwork.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-edgenetwork", - "version": "0.1.5" + "version": "0.1.6" }, "snippets": [ { diff --git a/packages/google-cloud-edgenetwork/setup.py b/packages/google-cloud-edgenetwork/setup.py index 6d57eb95fb50..0e138e51f4dd 100644 --- a/packages/google-cloud-edgenetwork/setup.py +++ b/packages/google-cloud-edgenetwork/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-enterpriseknowledgegraph/CHANGELOG.md b/packages/google-cloud-enterpriseknowledgegraph/CHANGELOG.md index 26743be60781..4c0f2c295aa8 100644 --- a/packages/google-cloud-enterpriseknowledgegraph/CHANGELOG.md +++ b/packages/google-cloud-enterpriseknowledgegraph/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.3.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-enterpriseknowledgegraph-v0.3.8...google-cloud-enterpriseknowledgegraph-v0.3.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [0.3.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-enterpriseknowledgegraph-v0.3.7...google-cloud-enterpriseknowledgegraph-v0.3.8) (2024-02-22) diff --git a/packages/google-cloud-enterpriseknowledgegraph/google/cloud/enterpriseknowledgegraph/gapic_version.py b/packages/google-cloud-enterpriseknowledgegraph/google/cloud/enterpriseknowledgegraph/gapic_version.py index 9c72996dc3e9..807d78fcb4c5 100644 --- a/packages/google-cloud-enterpriseknowledgegraph/google/cloud/enterpriseknowledgegraph/gapic_version.py +++ b/packages/google-cloud-enterpriseknowledgegraph/google/cloud/enterpriseknowledgegraph/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.8" # {x-release-please-version} +__version__ = "0.3.9" # {x-release-please-version} diff --git a/packages/google-cloud-enterpriseknowledgegraph/google/cloud/enterpriseknowledgegraph_v1/gapic_version.py b/packages/google-cloud-enterpriseknowledgegraph/google/cloud/enterpriseknowledgegraph_v1/gapic_version.py index 9c72996dc3e9..807d78fcb4c5 100644 --- a/packages/google-cloud-enterpriseknowledgegraph/google/cloud/enterpriseknowledgegraph_v1/gapic_version.py +++ b/packages/google-cloud-enterpriseknowledgegraph/google/cloud/enterpriseknowledgegraph_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.8" # {x-release-please-version} +__version__ = "0.3.9" # {x-release-please-version} diff --git a/packages/google-cloud-enterpriseknowledgegraph/samples/generated_samples/snippet_metadata_google.cloud.enterpriseknowledgegraph.v1.json b/packages/google-cloud-enterpriseknowledgegraph/samples/generated_samples/snippet_metadata_google.cloud.enterpriseknowledgegraph.v1.json index 3b2f041d70ec..19856bdf6b6b 100644 --- a/packages/google-cloud-enterpriseknowledgegraph/samples/generated_samples/snippet_metadata_google.cloud.enterpriseknowledgegraph.v1.json +++ b/packages/google-cloud-enterpriseknowledgegraph/samples/generated_samples/snippet_metadata_google.cloud.enterpriseknowledgegraph.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-enterpriseknowledgegraph", - "version": "0.3.8" + "version": "0.3.9" }, "snippets": [ { diff --git a/packages/google-cloud-enterpriseknowledgegraph/setup.py b/packages/google-cloud-enterpriseknowledgegraph/setup.py index 7ac1b1ad0a45..2ad382f0a25c 100644 --- a/packages/google-cloud-enterpriseknowledgegraph/setup.py +++ b/packages/google-cloud-enterpriseknowledgegraph/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-essential-contacts/CHANGELOG.md b/packages/google-cloud-essential-contacts/CHANGELOG.md index f352c01d752a..68ba74f6f117 100644 --- a/packages/google-cloud-essential-contacts/CHANGELOG.md +++ b/packages/google-cloud-essential-contacts/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.7.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-essential-contacts-v1.7.2...google-cloud-essential-contacts-v1.7.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [1.7.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-essential-contacts-v1.7.1...google-cloud-essential-contacts-v1.7.2) (2024-02-22) diff --git a/packages/google-cloud-essential-contacts/google/cloud/essential_contacts/gapic_version.py b/packages/google-cloud-essential-contacts/google/cloud/essential_contacts/gapic_version.py index a71edaad33ab..84f198c2d605 100644 --- a/packages/google-cloud-essential-contacts/google/cloud/essential_contacts/gapic_version.py +++ b/packages/google-cloud-essential-contacts/google/cloud/essential_contacts/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.7.2" # {x-release-please-version} +__version__ = "1.7.3" # {x-release-please-version} diff --git a/packages/google-cloud-essential-contacts/google/cloud/essential_contacts_v1/gapic_version.py b/packages/google-cloud-essential-contacts/google/cloud/essential_contacts_v1/gapic_version.py index a71edaad33ab..84f198c2d605 100644 --- a/packages/google-cloud-essential-contacts/google/cloud/essential_contacts_v1/gapic_version.py +++ b/packages/google-cloud-essential-contacts/google/cloud/essential_contacts_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.7.2" # {x-release-please-version} +__version__ = "1.7.3" # {x-release-please-version} diff --git a/packages/google-cloud-essential-contacts/samples/generated_samples/snippet_metadata_google.cloud.essentialcontacts.v1.json b/packages/google-cloud-essential-contacts/samples/generated_samples/snippet_metadata_google.cloud.essentialcontacts.v1.json index cc6832b2758a..d0aea0cd0212 100644 --- a/packages/google-cloud-essential-contacts/samples/generated_samples/snippet_metadata_google.cloud.essentialcontacts.v1.json +++ b/packages/google-cloud-essential-contacts/samples/generated_samples/snippet_metadata_google.cloud.essentialcontacts.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-essential-contacts", - "version": "1.7.2" + "version": "1.7.3" }, "snippets": [ { diff --git a/packages/google-cloud-essential-contacts/setup.py b/packages/google-cloud-essential-contacts/setup.py index 245e7d4209d4..ba9a165e78aa 100644 --- a/packages/google-cloud-essential-contacts/setup.py +++ b/packages/google-cloud-essential-contacts/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-eventarc-publishing/CHANGELOG.md b/packages/google-cloud-eventarc-publishing/CHANGELOG.md index 050f6762335f..d2793148e4e6 100644 --- a/packages/google-cloud-eventarc-publishing/CHANGELOG.md +++ b/packages/google-cloud-eventarc-publishing/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.6.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-eventarc-publishing-v0.6.8...google-cloud-eventarc-publishing-v0.6.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [0.6.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-eventarc-publishing-v0.6.7...google-cloud-eventarc-publishing-v0.6.8) (2024-02-22) diff --git a/packages/google-cloud-eventarc-publishing/eventarc-publishing-v1-py.tar.gz b/packages/google-cloud-eventarc-publishing/eventarc-publishing-v1-py.tar.gz new file mode 100644 index 000000000000..e69de29bb2d1 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 93768f73f8ae..5106807e66a2 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.8" # {x-release-please-version} +__version__ = "0.6.9" # {x-release-please-version} 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 93768f73f8ae..5106807e66a2 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.8" # {x-release-please-version} +__version__ = "0.6.9" # {x-release-please-version} 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 da6c4691de8d..bebb319c24d8 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.8" + "version": "0.6.9" }, "snippets": [ { diff --git a/packages/google-cloud-eventarc-publishing/setup.py b/packages/google-cloud-eventarc-publishing/setup.py index 0fc6b28ac971..8d6f60b44c7d 100644 --- a/packages/google-cloud-eventarc-publishing/setup.py +++ b/packages/google-cloud-eventarc-publishing/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-eventarc/CHANGELOG.md b/packages/google-cloud-eventarc/CHANGELOG.md index 3df268d61945..49f589e91043 100644 --- a/packages/google-cloud-eventarc/CHANGELOG.md +++ b/packages/google-cloud-eventarc/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.11.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-eventarc-v1.11.2...google-cloud-eventarc-v1.11.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [1.11.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-eventarc-v1.11.1...google-cloud-eventarc-v1.11.2) (2024-02-22) 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 787a045996f3..88fbabfeb794 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.11.2" # {x-release-please-version} +__version__ = "1.11.3" # {x-release-please-version} 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 787a045996f3..88fbabfeb794 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.11.2" # {x-release-please-version} +__version__ = "1.11.3" # {x-release-please-version} 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 476d685043dc..17618fae19af 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.11.2" + "version": "1.11.3" }, "snippets": [ { diff --git a/packages/google-cloud-eventarc/setup.py b/packages/google-cloud-eventarc/setup.py index ccf022def329..aff86adc51ec 100644 --- a/packages/google-cloud-eventarc/setup.py +++ b/packages/google-cloud-eventarc/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-filestore/CHANGELOG.md b/packages/google-cloud-filestore/CHANGELOG.md index bacc4dae3cd6..8077f00bc816 100644 --- a/packages/google-cloud-filestore/CHANGELOG.md +++ b/packages/google-cloud-filestore/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.9.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-filestore-v1.9.2...google-cloud-filestore-v1.9.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [1.9.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-filestore-v1.9.1...google-cloud-filestore-v1.9.2) (2024-02-22) diff --git a/packages/google-cloud-filestore/google/cloud/filestore/gapic_version.py b/packages/google-cloud-filestore/google/cloud/filestore/gapic_version.py index f14078b6f555..ec42a8e289c4 100644 --- a/packages/google-cloud-filestore/google/cloud/filestore/gapic_version.py +++ b/packages/google-cloud-filestore/google/cloud/filestore/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} diff --git a/packages/google-cloud-filestore/google/cloud/filestore_v1/gapic_version.py b/packages/google-cloud-filestore/google/cloud/filestore_v1/gapic_version.py index f14078b6f555..ec42a8e289c4 100644 --- a/packages/google-cloud-filestore/google/cloud/filestore_v1/gapic_version.py +++ b/packages/google-cloud-filestore/google/cloud/filestore_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} diff --git a/packages/google-cloud-filestore/samples/generated_samples/snippet_metadata_google.cloud.filestore.v1.json b/packages/google-cloud-filestore/samples/generated_samples/snippet_metadata_google.cloud.filestore.v1.json index f638cadd79ac..775572274534 100644 --- a/packages/google-cloud-filestore/samples/generated_samples/snippet_metadata_google.cloud.filestore.v1.json +++ b/packages/google-cloud-filestore/samples/generated_samples/snippet_metadata_google.cloud.filestore.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-filestore", - "version": "1.9.2" + "version": "1.9.3" }, "snippets": [ { diff --git a/packages/google-cloud-filestore/setup.py b/packages/google-cloud-filestore/setup.py index ecba1c304d88..b48bf0d7e9c4 100644 --- a/packages/google-cloud-filestore/setup.py +++ b/packages/google-cloud-filestore/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "google-cloud-common >= 1.0.0, <2.0.0dev", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", diff --git a/packages/google-cloud-functions/CHANGELOG.md b/packages/google-cloud-functions/CHANGELOG.md index 3854be88eb99..7ee517430b97 100644 --- a/packages/google-cloud-functions/CHANGELOG.md +++ b/packages/google-cloud-functions/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.16.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-functions-v1.16.2...google-cloud-functions-v1.16.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [1.16.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-functions-v1.16.1...google-cloud-functions-v1.16.2) (2024-02-22) diff --git a/packages/google-cloud-functions/google/cloud/functions/gapic_version.py b/packages/google-cloud-functions/google/cloud/functions/gapic_version.py index b55506440976..d2beef6a64b8 100644 --- a/packages/google-cloud-functions/google/cloud/functions/gapic_version.py +++ b/packages/google-cloud-functions/google/cloud/functions/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.16.2" # {x-release-please-version} +__version__ = "1.16.3" # {x-release-please-version} diff --git a/packages/google-cloud-functions/google/cloud/functions_v1/gapic_version.py b/packages/google-cloud-functions/google/cloud/functions_v1/gapic_version.py index b55506440976..d2beef6a64b8 100644 --- a/packages/google-cloud-functions/google/cloud/functions_v1/gapic_version.py +++ b/packages/google-cloud-functions/google/cloud/functions_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.2" # {x-release-please-version} +__version__ = "1.16.3" # {x-release-please-version} diff --git a/packages/google-cloud-functions/google/cloud/functions_v2/gapic_version.py b/packages/google-cloud-functions/google/cloud/functions_v2/gapic_version.py index b55506440976..d2beef6a64b8 100644 --- a/packages/google-cloud-functions/google/cloud/functions_v2/gapic_version.py +++ b/packages/google-cloud-functions/google/cloud/functions_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.16.2" # {x-release-please-version} +__version__ = "1.16.3" # {x-release-please-version} diff --git a/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_google.cloud.functions.v1.json b/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_google.cloud.functions.v1.json index 23fb3eb7fba3..2e8307fc01bf 100644 --- a/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_google.cloud.functions.v1.json +++ b/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_google.cloud.functions.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-functions", - "version": "1.16.2" + "version": "1.16.3" }, "snippets": [ { diff --git a/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_google.cloud.functions.v2.json b/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_google.cloud.functions.v2.json index 27dab97b121e..5c2f9cb9ff14 100644 --- a/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_google.cloud.functions.v2.json +++ b/packages/google-cloud-functions/samples/generated_samples/snippet_metadata_google.cloud.functions.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-functions", - "version": "1.16.2" + "version": "1.16.3" }, "snippets": [ { diff --git a/packages/google-cloud-functions/setup.py b/packages/google-cloud-functions/setup.py index a19ca5de8e76..dbd984495808 100644 --- a/packages/google-cloud-functions/setup.py +++ b/packages/google-cloud-functions/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-gke-backup/CHANGELOG.md b/packages/google-cloud-gke-backup/CHANGELOG.md index 0e69fc3d420d..6866f11db122 100644 --- a/packages/google-cloud-gke-backup/CHANGELOG.md +++ b/packages/google-cloud-gke-backup/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.5.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-gke-backup-v0.5.6...google-cloud-gke-backup-v0.5.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [0.5.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-gke-backup-v0.5.5...google-cloud-gke-backup-v0.5.6) (2024-02-22) diff --git a/packages/google-cloud-gke-backup/google/cloud/gke_backup/gapic_version.py b/packages/google-cloud-gke-backup/google/cloud/gke_backup/gapic_version.py index 707b752e07d4..525ae0137447 100644 --- a/packages/google-cloud-gke-backup/google/cloud/gke_backup/gapic_version.py +++ b/packages/google-cloud-gke-backup/google/cloud/gke_backup/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.6" # {x-release-please-version} +__version__ = "0.5.7" # {x-release-please-version} diff --git a/packages/google-cloud-gke-backup/google/cloud/gke_backup_v1/gapic_version.py b/packages/google-cloud-gke-backup/google/cloud/gke_backup_v1/gapic_version.py index 707b752e07d4..525ae0137447 100644 --- a/packages/google-cloud-gke-backup/google/cloud/gke_backup_v1/gapic_version.py +++ b/packages/google-cloud-gke-backup/google/cloud/gke_backup_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.6" # {x-release-please-version} +__version__ = "0.5.7" # {x-release-please-version} diff --git a/packages/google-cloud-gke-backup/samples/generated_samples/snippet_metadata_google.cloud.gkebackup.v1.json b/packages/google-cloud-gke-backup/samples/generated_samples/snippet_metadata_google.cloud.gkebackup.v1.json index 5fabefaa57bc..fbbc49a6b03d 100644 --- a/packages/google-cloud-gke-backup/samples/generated_samples/snippet_metadata_google.cloud.gkebackup.v1.json +++ b/packages/google-cloud-gke-backup/samples/generated_samples/snippet_metadata_google.cloud.gkebackup.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-gke-backup", - "version": "0.5.6" + "version": "0.5.7" }, "snippets": [ { diff --git a/packages/google-cloud-gke-backup/setup.py b/packages/google-cloud-gke-backup/setup.py index 55834eee7a41..fb8d6add6d53 100644 --- a/packages/google-cloud-gke-backup/setup.py +++ b/packages/google-cloud-gke-backup/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-gke-connect-gateway/CHANGELOG.md b/packages/google-cloud-gke-connect-gateway/CHANGELOG.md index 0f15e2b3ae8b..96fa678983f3 100644 --- a/packages/google-cloud-gke-connect-gateway/CHANGELOG.md +++ b/packages/google-cloud-gke-connect-gateway/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.8.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-gke-connect-gateway-v0.8.8...google-cloud-gke-connect-gateway-v0.8.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [0.8.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-gke-connect-gateway-v0.8.7...google-cloud-gke-connect-gateway-v0.8.8) (2024-02-22) diff --git a/packages/google-cloud-gke-connect-gateway/google/cloud/gkeconnect/gateway/gapic_version.py b/packages/google-cloud-gke-connect-gateway/google/cloud/gkeconnect/gateway/gapic_version.py index 0ec866e857d0..f0250f692033 100644 --- a/packages/google-cloud-gke-connect-gateway/google/cloud/gkeconnect/gateway/gapic_version.py +++ b/packages/google-cloud-gke-connect-gateway/google/cloud/gkeconnect/gateway/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.8.8" # {x-release-please-version} +__version__ = "0.8.9" # {x-release-please-version} diff --git a/packages/google-cloud-gke-connect-gateway/google/cloud/gkeconnect/gateway_v1beta1/gapic_version.py b/packages/google-cloud-gke-connect-gateway/google/cloud/gkeconnect/gateway_v1beta1/gapic_version.py index 0ec866e857d0..f0250f692033 100644 --- a/packages/google-cloud-gke-connect-gateway/google/cloud/gkeconnect/gateway_v1beta1/gapic_version.py +++ b/packages/google-cloud-gke-connect-gateway/google/cloud/gkeconnect/gateway_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.8.8" # {x-release-please-version} +__version__ = "0.8.9" # {x-release-please-version} diff --git a/packages/google-cloud-gke-connect-gateway/samples/generated_samples/snippet_metadata_google.cloud.gkeconnect.gateway.v1beta1.json b/packages/google-cloud-gke-connect-gateway/samples/generated_samples/snippet_metadata_google.cloud.gkeconnect.gateway.v1beta1.json index 22e4a2f7c14b..f6989d41a71e 100644 --- a/packages/google-cloud-gke-connect-gateway/samples/generated_samples/snippet_metadata_google.cloud.gkeconnect.gateway.v1beta1.json +++ b/packages/google-cloud-gke-connect-gateway/samples/generated_samples/snippet_metadata_google.cloud.gkeconnect.gateway.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-gke-connect-gateway", - "version": "0.8.8" + "version": "0.8.9" }, "snippets": [ { diff --git a/packages/google-cloud-gke-connect-gateway/setup.py b/packages/google-cloud-gke-connect-gateway/setup.py index 26c00bab558e..e332907add7a 100644 --- a/packages/google-cloud-gke-connect-gateway/setup.py +++ b/packages/google-cloud-gke-connect-gateway/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-gke-hub/CHANGELOG.md b/packages/google-cloud-gke-hub/CHANGELOG.md index 535bdf1d6c6a..9ae00f06b5a6 100644 --- a/packages/google-cloud-gke-hub/CHANGELOG.md +++ b/packages/google-cloud-gke-hub/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.13.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-gke-hub-v1.13.0...google-cloud-gke-hub-v1.13.1) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12384](https://github.com/googleapis/google-cloud-python/issues/12384)) ([c69966f](https://github.com/googleapis/google-cloud-python/commit/c69966fa7aac2cba4e22513e4a053b3754f8ea5e)) + ## [1.13.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-gke-hub-v1.12.1...google-cloud-gke-hub-v1.13.0) (2024-02-22) diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub/gapic_version.py b/packages/google-cloud-gke-hub/google/cloud/gkehub/gapic_version.py index 45be25c513a7..6b5026510a1c 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub/gapic_version.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub/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-gke-hub/google/cloud/gkehub_v1/configmanagement_v1/gapic_version.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/configmanagement_v1/gapic_version.py index 45be25c513a7..6b5026510a1c 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/configmanagement_v1/gapic_version.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/configmanagement_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-gke-hub/google/cloud/gkehub_v1/gapic_version.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/gapic_version.py index 45be25c513a7..6b5026510a1c 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/gapic_version.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_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-gke-hub/google/cloud/gkehub_v1/multiclusteringress_v1/gapic_version.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/multiclusteringress_v1/gapic_version.py index 45be25c513a7..6b5026510a1c 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/multiclusteringress_v1/gapic_version.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/multiclusteringress_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-gke-hub/google/cloud/gkehub_v1beta1/gapic_version.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/gapic_version.py index 45be25c513a7..6b5026510a1c 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1beta1/gapic_version.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_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-gke-hub/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1.json b/packages/google-cloud-gke-hub/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1.json index 438f8bef1d49..83ad56529785 100644 --- a/packages/google-cloud-gke-hub/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1.json +++ b/packages/google-cloud-gke-hub/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-gke-hub", - "version": "1.13.0" + "version": "1.13.1" }, "snippets": [ { diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1beta1.json b/packages/google-cloud-gke-hub/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1beta1.json index b7f38b612352..3951629fa743 100644 --- a/packages/google-cloud-gke-hub/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1beta1.json +++ b/packages/google-cloud-gke-hub/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-gke-hub", - "version": "1.13.0" + "version": "1.13.1" }, "snippets": [ { diff --git a/packages/google-cloud-gke-hub/setup.py b/packages/google-cloud-gke-hub/setup.py index f6c459698991..df05caa81d80 100644 --- a/packages/google-cloud-gke-hub/setup.py +++ b/packages/google-cloud-gke-hub/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "grpc-google-iam-v1 >=0.12.4, <1.0.0dev", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", diff --git a/packages/google-cloud-gke-multicloud/CHANGELOG.md b/packages/google-cloud-gke-multicloud/CHANGELOG.md index 86d513c70579..8fe14f4153ac 100644 --- a/packages/google-cloud-gke-multicloud/CHANGELOG.md +++ b/packages/google-cloud-gke-multicloud/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.6.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-gke-multicloud-v0.6.8...google-cloud-gke-multicloud-v0.6.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [0.6.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-gke-multicloud-v0.6.7...google-cloud-gke-multicloud-v0.6.8) (2024-02-22) diff --git a/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud/gapic_version.py b/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud/gapic_version.py index 93768f73f8ae..5106807e66a2 100644 --- a/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud/gapic_version.py +++ b/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.8" # {x-release-please-version} +__version__ = "0.6.9" # {x-release-please-version} diff --git a/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud_v1/gapic_version.py b/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud_v1/gapic_version.py index 93768f73f8ae..5106807e66a2 100644 --- a/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud_v1/gapic_version.py +++ b/packages/google-cloud-gke-multicloud/google/cloud/gke_multicloud_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.8" # {x-release-please-version} +__version__ = "0.6.9" # {x-release-please-version} diff --git a/packages/google-cloud-gke-multicloud/samples/generated_samples/snippet_metadata_google.cloud.gkemulticloud.v1.json b/packages/google-cloud-gke-multicloud/samples/generated_samples/snippet_metadata_google.cloud.gkemulticloud.v1.json index 0b072db4e44b..a0ec92751fd9 100644 --- a/packages/google-cloud-gke-multicloud/samples/generated_samples/snippet_metadata_google.cloud.gkemulticloud.v1.json +++ b/packages/google-cloud-gke-multicloud/samples/generated_samples/snippet_metadata_google.cloud.gkemulticloud.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-gke-multicloud", - "version": "0.6.8" + "version": "0.6.9" }, "snippets": [ { diff --git a/packages/google-cloud-gke-multicloud/setup.py b/packages/google-cloud-gke-multicloud/setup.py index f8d6b1cc0df1..173d9e37b536 100644 --- a/packages/google-cloud-gke-multicloud/setup.py +++ b/packages/google-cloud-gke-multicloud/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-gsuiteaddons/CHANGELOG.md b/packages/google-cloud-gsuiteaddons/CHANGELOG.md index 4b89e1d587e2..588b4f4d87e1 100644 --- a/packages/google-cloud-gsuiteaddons/CHANGELOG.md +++ b/packages/google-cloud-gsuiteaddons/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.3.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-gsuiteaddons-v0.3.7...google-cloud-gsuiteaddons-v0.3.8) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [0.3.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-gsuiteaddons-v0.3.6...google-cloud-gsuiteaddons-v0.3.7) (2024-02-22) diff --git a/packages/google-cloud-gsuiteaddons/google/cloud/gsuiteaddons/gapic_version.py b/packages/google-cloud-gsuiteaddons/google/cloud/gsuiteaddons/gapic_version.py index 91090a840535..9c72996dc3e9 100644 --- a/packages/google-cloud-gsuiteaddons/google/cloud/gsuiteaddons/gapic_version.py +++ b/packages/google-cloud-gsuiteaddons/google/cloud/gsuiteaddons/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.7" # {x-release-please-version} +__version__ = "0.3.8" # {x-release-please-version} diff --git a/packages/google-cloud-gsuiteaddons/google/cloud/gsuiteaddons_v1/gapic_version.py b/packages/google-cloud-gsuiteaddons/google/cloud/gsuiteaddons_v1/gapic_version.py index 91090a840535..9c72996dc3e9 100644 --- a/packages/google-cloud-gsuiteaddons/google/cloud/gsuiteaddons_v1/gapic_version.py +++ b/packages/google-cloud-gsuiteaddons/google/cloud/gsuiteaddons_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.7" # {x-release-please-version} +__version__ = "0.3.8" # {x-release-please-version} diff --git a/packages/google-cloud-gsuiteaddons/samples/generated_samples/snippet_metadata_google.cloud.gsuiteaddons.v1.json b/packages/google-cloud-gsuiteaddons/samples/generated_samples/snippet_metadata_google.cloud.gsuiteaddons.v1.json index 949b681cbd81..9c40843a6abe 100644 --- a/packages/google-cloud-gsuiteaddons/samples/generated_samples/snippet_metadata_google.cloud.gsuiteaddons.v1.json +++ b/packages/google-cloud-gsuiteaddons/samples/generated_samples/snippet_metadata_google.cloud.gsuiteaddons.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-gsuiteaddons", - "version": "0.3.7" + "version": "0.3.8" }, "snippets": [ { diff --git a/packages/google-cloud-gsuiteaddons/setup.py b/packages/google-cloud-gsuiteaddons/setup.py index 00b3e0439df9..cda35ea6099e 100644 --- a/packages/google-cloud-gsuiteaddons/setup.py +++ b/packages/google-cloud-gsuiteaddons/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "google-apps-script-type >= 0.2.0, <1.0.0dev", diff --git a/packages/google-cloud-iam-logging/CHANGELOG.md b/packages/google-cloud-iam-logging/CHANGELOG.md index 09db496c0579..7db6630362ed 100644 --- a/packages/google-cloud-iam-logging/CHANGELOG.md +++ b/packages/google-cloud-iam-logging/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.3.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-iam-logging-v1.3.2...google-cloud-iam-logging-v1.3.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [1.3.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-iam-logging-v1.3.1...google-cloud-iam-logging-v1.3.2) (2024-02-22) diff --git a/packages/google-cloud-iam-logging/google/cloud/iam_logging/gapic_version.py b/packages/google-cloud-iam-logging/google/cloud/iam_logging/gapic_version.py index 7446194bbca6..f4b33bf9176f 100644 --- a/packages/google-cloud-iam-logging/google/cloud/iam_logging/gapic_version.py +++ b/packages/google-cloud-iam-logging/google/cloud/iam_logging/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.3.2" # {x-release-please-version} +__version__ = "1.3.3" # {x-release-please-version} diff --git a/packages/google-cloud-iam-logging/google/cloud/iam_logging_v1/gapic_version.py b/packages/google-cloud-iam-logging/google/cloud/iam_logging_v1/gapic_version.py index 7446194bbca6..f4b33bf9176f 100644 --- a/packages/google-cloud-iam-logging/google/cloud/iam_logging_v1/gapic_version.py +++ b/packages/google-cloud-iam-logging/google/cloud/iam_logging_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.3.2" # {x-release-please-version} +__version__ = "1.3.3" # {x-release-please-version} diff --git a/packages/google-cloud-iam-logging/setup.py b/packages/google-cloud-iam-logging/setup.py index 93b428cba756..0ebd6acb9350 100644 --- a/packages/google-cloud-iam-logging/setup.py +++ b/packages/google-cloud-iam-logging/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-iam/CHANGELOG.md b/packages/google-cloud-iam/CHANGELOG.md index 47dc93f22ba8..c27e9bb5375f 100644 --- a/packages/google-cloud-iam/CHANGELOG.md +++ b/packages/google-cloud-iam/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-iam/#history +## [2.14.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-iam-v2.14.2...google-cloud-iam-v2.14.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [2.14.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-iam-v2.14.1...google-cloud-iam-v2.14.2) (2024-02-22) diff --git a/packages/google-cloud-iam/google/cloud/iam/gapic_version.py b/packages/google-cloud-iam/google/cloud/iam/gapic_version.py index e00709b42b8e..6440b3563e45 100644 --- a/packages/google-cloud-iam/google/cloud/iam/gapic_version.py +++ b/packages/google-cloud-iam/google/cloud/iam/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.14.2" # {x-release-please-version} +__version__ = "2.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-iam/google/cloud/iam_credentials/gapic_version.py b/packages/google-cloud-iam/google/cloud/iam_credentials/gapic_version.py index e00709b42b8e..6440b3563e45 100644 --- a/packages/google-cloud-iam/google/cloud/iam_credentials/gapic_version.py +++ b/packages/google-cloud-iam/google/cloud/iam_credentials/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.14.2" # {x-release-please-version} +__version__ = "2.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-iam/google/cloud/iam_credentials_v1/gapic_version.py b/packages/google-cloud-iam/google/cloud/iam_credentials_v1/gapic_version.py index e00709b42b8e..6440b3563e45 100644 --- a/packages/google-cloud-iam/google/cloud/iam_credentials_v1/gapic_version.py +++ b/packages/google-cloud-iam/google/cloud/iam_credentials_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.2" # {x-release-please-version} +__version__ = "2.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-iam/google/cloud/iam_v2/gapic_version.py b/packages/google-cloud-iam/google/cloud/iam_v2/gapic_version.py index e00709b42b8e..6440b3563e45 100644 --- a/packages/google-cloud-iam/google/cloud/iam_v2/gapic_version.py +++ b/packages/google-cloud-iam/google/cloud/iam_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.14.2" # {x-release-please-version} +__version__ = "2.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-iam/google/cloud/iam_v2beta/gapic_version.py b/packages/google-cloud-iam/google/cloud/iam_v2beta/gapic_version.py index e00709b42b8e..6440b3563e45 100644 --- a/packages/google-cloud-iam/google/cloud/iam_v2beta/gapic_version.py +++ b/packages/google-cloud-iam/google/cloud/iam_v2beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.14.2" # {x-release-please-version} +__version__ = "2.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-iam/samples/generated_samples/snippet_metadata_google.iam.credentials.v1.json b/packages/google-cloud-iam/samples/generated_samples/snippet_metadata_google.iam.credentials.v1.json index 98303aebe43e..fc8ae8b4132c 100644 --- a/packages/google-cloud-iam/samples/generated_samples/snippet_metadata_google.iam.credentials.v1.json +++ b/packages/google-cloud-iam/samples/generated_samples/snippet_metadata_google.iam.credentials.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-iam", - "version": "2.14.2" + "version": "2.14.3" }, "snippets": [ { diff --git a/packages/google-cloud-iam/samples/generated_samples/snippet_metadata_google.iam.v2.json b/packages/google-cloud-iam/samples/generated_samples/snippet_metadata_google.iam.v2.json index b03d2454e2a8..965c5981be0b 100644 --- a/packages/google-cloud-iam/samples/generated_samples/snippet_metadata_google.iam.v2.json +++ b/packages/google-cloud-iam/samples/generated_samples/snippet_metadata_google.iam.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-iam", - "version": "2.14.2" + "version": "2.14.3" }, "snippets": [ { diff --git a/packages/google-cloud-iam/samples/generated_samples/snippet_metadata_google.iam.v2beta.json b/packages/google-cloud-iam/samples/generated_samples/snippet_metadata_google.iam.v2beta.json index 89a6d2a58710..8428b66651e7 100644 --- a/packages/google-cloud-iam/samples/generated_samples/snippet_metadata_google.iam.v2beta.json +++ b/packages/google-cloud-iam/samples/generated_samples/snippet_metadata_google.iam.v2beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-iam", - "version": "2.14.2" + "version": "2.14.3" }, "snippets": [ { diff --git a/packages/google-cloud-iam/setup.py b/packages/google-cloud-iam/setup.py index 833e7d5d61b2..1538d2e14d63 100644 --- a/packages/google-cloud-iam/setup.py +++ b/packages/google-cloud-iam/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-iap/CHANGELOG.md b/packages/google-cloud-iap/CHANGELOG.md index fb2a5bd4dffe..050a80f91f72 100644 --- a/packages/google-cloud-iap/CHANGELOG.md +++ b/packages/google-cloud-iap/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.13.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-iap-v1.13.2...google-cloud-iap-v1.13.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [1.13.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-iap-v1.13.1...google-cloud-iap-v1.13.2) (2024-02-22) diff --git a/packages/google-cloud-iap/google/cloud/iap/gapic_version.py b/packages/google-cloud-iap/google/cloud/iap/gapic_version.py index 3434b217efee..40e034931fac 100644 --- a/packages/google-cloud-iap/google/cloud/iap/gapic_version.py +++ b/packages/google-cloud-iap/google/cloud/iap/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.13.2" # {x-release-please-version} +__version__ = "1.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-iap/google/cloud/iap_v1/gapic_version.py b/packages/google-cloud-iap/google/cloud/iap_v1/gapic_version.py index 3434b217efee..40e034931fac 100644 --- a/packages/google-cloud-iap/google/cloud/iap_v1/gapic_version.py +++ b/packages/google-cloud-iap/google/cloud/iap_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.2" # {x-release-please-version} +__version__ = "1.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-iap/samples/generated_samples/snippet_metadata_google.cloud.iap.v1.json b/packages/google-cloud-iap/samples/generated_samples/snippet_metadata_google.cloud.iap.v1.json index 6f3ec27b602f..6d5df320a397 100644 --- a/packages/google-cloud-iap/samples/generated_samples/snippet_metadata_google.cloud.iap.v1.json +++ b/packages/google-cloud-iap/samples/generated_samples/snippet_metadata_google.cloud.iap.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-iap", - "version": "1.13.2" + "version": "1.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-iap/setup.py b/packages/google-cloud-iap/setup.py index 9a233e7adf1e..d72e19235ff1 100644 --- a/packages/google-cloud-iap/setup.py +++ b/packages/google-cloud-iap/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-ids/CHANGELOG.md b/packages/google-cloud-ids/CHANGELOG.md index 221eaa1d4299..8175731856c1 100644 --- a/packages/google-cloud-ids/CHANGELOG.md +++ b/packages/google-cloud-ids/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.7.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-ids-v1.7.2...google-cloud-ids-v1.7.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [1.7.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-ids-v1.7.1...google-cloud-ids-v1.7.2) (2024-02-22) diff --git a/packages/google-cloud-ids/google/cloud/ids/gapic_version.py b/packages/google-cloud-ids/google/cloud/ids/gapic_version.py index a71edaad33ab..84f198c2d605 100644 --- a/packages/google-cloud-ids/google/cloud/ids/gapic_version.py +++ b/packages/google-cloud-ids/google/cloud/ids/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.7.2" # {x-release-please-version} +__version__ = "1.7.3" # {x-release-please-version} diff --git a/packages/google-cloud-ids/google/cloud/ids_v1/gapic_version.py b/packages/google-cloud-ids/google/cloud/ids_v1/gapic_version.py index a71edaad33ab..84f198c2d605 100644 --- a/packages/google-cloud-ids/google/cloud/ids_v1/gapic_version.py +++ b/packages/google-cloud-ids/google/cloud/ids_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.7.2" # {x-release-please-version} +__version__ = "1.7.3" # {x-release-please-version} diff --git a/packages/google-cloud-ids/samples/generated_samples/snippet_metadata_google.cloud.ids.v1.json b/packages/google-cloud-ids/samples/generated_samples/snippet_metadata_google.cloud.ids.v1.json index c5edaff0ba49..75fa95ed3178 100644 --- a/packages/google-cloud-ids/samples/generated_samples/snippet_metadata_google.cloud.ids.v1.json +++ b/packages/google-cloud-ids/samples/generated_samples/snippet_metadata_google.cloud.ids.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-ids", - "version": "1.7.2" + "version": "1.7.3" }, "snippets": [ { diff --git a/packages/google-cloud-ids/setup.py b/packages/google-cloud-ids/setup.py index bfbbfea9faeb..afb27fa2dbc5 100644 --- a/packages/google-cloud-ids/setup.py +++ b/packages/google-cloud-ids/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-kms-inventory/CHANGELOG.md b/packages/google-cloud-kms-inventory/CHANGELOG.md index f376df16d4b5..8496a5a50f50 100644 --- a/packages/google-cloud-kms-inventory/CHANGELOG.md +++ b/packages/google-cloud-kms-inventory/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.2.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-kms-inventory-v0.2.5...google-cloud-kms-inventory-v0.2.6) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [0.2.5](https://github.com/googleapis/google-cloud-python/compare/google-cloud-kms-inventory-v0.2.4...google-cloud-kms-inventory-v0.2.5) (2024-02-22) diff --git a/packages/google-cloud-kms-inventory/google/cloud/kms_inventory/gapic_version.py b/packages/google-cloud-kms-inventory/google/cloud/kms_inventory/gapic_version.py index 2c392be2b92b..6ec6b5dedd5b 100644 --- a/packages/google-cloud-kms-inventory/google/cloud/kms_inventory/gapic_version.py +++ b/packages/google-cloud-kms-inventory/google/cloud/kms_inventory/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.2.5" # {x-release-please-version} +__version__ = "0.2.6" # {x-release-please-version} diff --git a/packages/google-cloud-kms-inventory/google/cloud/kms_inventory_v1/gapic_version.py b/packages/google-cloud-kms-inventory/google/cloud/kms_inventory_v1/gapic_version.py index 2c392be2b92b..6ec6b5dedd5b 100644 --- a/packages/google-cloud-kms-inventory/google/cloud/kms_inventory_v1/gapic_version.py +++ b/packages/google-cloud-kms-inventory/google/cloud/kms_inventory_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.5" # {x-release-please-version} +__version__ = "0.2.6" # {x-release-please-version} diff --git a/packages/google-cloud-kms-inventory/samples/generated_samples/snippet_metadata_google.cloud.kms.inventory.v1.json b/packages/google-cloud-kms-inventory/samples/generated_samples/snippet_metadata_google.cloud.kms.inventory.v1.json index f768d778d6b1..6eca8e57f34a 100644 --- a/packages/google-cloud-kms-inventory/samples/generated_samples/snippet_metadata_google.cloud.kms.inventory.v1.json +++ b/packages/google-cloud-kms-inventory/samples/generated_samples/snippet_metadata_google.cloud.kms.inventory.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-kms-inventory", - "version": "0.2.5" + "version": "0.2.6" }, "snippets": [ { diff --git a/packages/google-cloud-kms-inventory/setup.py b/packages/google-cloud-kms-inventory/setup.py index f1b3e0c60c6b..55d4e65b5d87 100644 --- a/packages/google-cloud-kms-inventory/setup.py +++ b/packages/google-cloud-kms-inventory/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "google-cloud-kms >= 2.3.0, <3.0.0dev", diff --git a/packages/google-cloud-kms/CHANGELOG.md b/packages/google-cloud-kms/CHANGELOG.md index 3cec841a562f..9ea60b630409 100644 --- a/packages/google-cloud-kms/CHANGELOG.md +++ b/packages/google-cloud-kms/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-kms/#history +## [2.21.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-kms-v2.21.2...google-cloud-kms-v2.21.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [2.21.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-kms-v2.21.1...google-cloud-kms-v2.21.2) (2024-02-22) diff --git a/packages/google-cloud-kms/google/cloud/kms/gapic_version.py b/packages/google-cloud-kms/google/cloud/kms/gapic_version.py index 4cea3531fd4c..50e74a83eb6e 100644 --- a/packages/google-cloud-kms/google/cloud/kms/gapic_version.py +++ b/packages/google-cloud-kms/google/cloud/kms/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.21.2" # {x-release-please-version} +__version__ = "2.21.3" # {x-release-please-version} diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/gapic_version.py b/packages/google-cloud-kms/google/cloud/kms_v1/gapic_version.py index 4cea3531fd4c..50e74a83eb6e 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/gapic_version.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.21.2" # {x-release-please-version} +__version__ = "2.21.3" # {x-release-please-version} diff --git a/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json b/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json index c6271c2147b8..fa76b623a2eb 100644 --- a/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json +++ b/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-kms", - "version": "2.21.2" + "version": "2.21.3" }, "snippets": [ { diff --git a/packages/google-cloud-kms/setup.py b/packages/google-cloud-kms/setup.py index 82e0da946c6c..a70cf4e5f551 100644 --- a/packages/google-cloud-kms/setup.py +++ b/packages/google-cloud-kms/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-language/CHANGELOG.md b/packages/google-cloud-language/CHANGELOG.md index de9e65b77def..2e84ecd98539 100644 --- a/packages/google-cloud-language/CHANGELOG.md +++ b/packages/google-cloud-language/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-language/#history +## [2.13.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-language-v2.13.2...google-cloud-language-v2.13.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [2.13.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-language-v2.13.1...google-cloud-language-v2.13.2) (2024-02-22) diff --git a/packages/google-cloud-language/google/cloud/language/gapic_version.py b/packages/google-cloud-language/google/cloud/language/gapic_version.py index d767d5ad8591..6c235a092e73 100644 --- a/packages/google-cloud-language/google/cloud/language/gapic_version.py +++ b/packages/google-cloud-language/google/cloud/language/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-language/google/cloud/language_v1/gapic_version.py b/packages/google-cloud-language/google/cloud/language_v1/gapic_version.py index d767d5ad8591..6c235a092e73 100644 --- a/packages/google-cloud-language/google/cloud/language_v1/gapic_version.py +++ b/packages/google-cloud-language/google/cloud/language_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-language/google/cloud/language_v1beta2/gapic_version.py b/packages/google-cloud-language/google/cloud/language_v1beta2/gapic_version.py index d767d5ad8591..6c235a092e73 100644 --- a/packages/google-cloud-language/google/cloud/language_v1beta2/gapic_version.py +++ b/packages/google-cloud-language/google/cloud/language_v1beta2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-language/google/cloud/language_v2/gapic_version.py b/packages/google-cloud-language/google/cloud/language_v2/gapic_version.py index d767d5ad8591..6c235a092e73 100644 --- a/packages/google-cloud-language/google/cloud/language_v2/gapic_version.py +++ b/packages/google-cloud-language/google/cloud/language_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-language/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json b/packages/google-cloud-language/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json index e52c15c1d9a6..c5b8aec8656c 100644 --- a/packages/google-cloud-language/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json +++ b/packages/google-cloud-language/samples/generated_samples/snippet_metadata_google.cloud.language.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "2.13.2" + "version": "2.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-language/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json b/packages/google-cloud-language/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json index 6b922458d71c..ba9dbbbee608 100644 --- a/packages/google-cloud-language/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json +++ b/packages/google-cloud-language/samples/generated_samples/snippet_metadata_google.cloud.language.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "2.13.2" + "version": "2.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-language/samples/generated_samples/snippet_metadata_google.cloud.language.v2.json b/packages/google-cloud-language/samples/generated_samples/snippet_metadata_google.cloud.language.v2.json index b75b87024a7a..cbe96d939fbc 100644 --- a/packages/google-cloud-language/samples/generated_samples/snippet_metadata_google.cloud.language.v2.json +++ b/packages/google-cloud-language/samples/generated_samples/snippet_metadata_google.cloud.language.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-language", - "version": "2.13.2" + "version": "2.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-language/setup.py b/packages/google-cloud-language/setup.py index 63e14f5e8bf2..026f80a8b9a9 100644 --- a/packages/google-cloud-language/setup.py +++ b/packages/google-cloud-language/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-life-sciences/CHANGELOG.md b/packages/google-cloud-life-sciences/CHANGELOG.md index 8b1c05bff649..8b712db15357 100644 --- a/packages/google-cloud-life-sciences/CHANGELOG.md +++ b/packages/google-cloud-life-sciences/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.9.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-life-sciences-v0.9.8...google-cloud-life-sciences-v0.9.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [0.9.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-life-sciences-v0.9.7...google-cloud-life-sciences-v0.9.8) (2024-02-22) diff --git a/packages/google-cloud-life-sciences/google/cloud/lifesciences/gapic_version.py b/packages/google-cloud-life-sciences/google/cloud/lifesciences/gapic_version.py index 766951197b66..301bd68cc9f0 100644 --- a/packages/google-cloud-life-sciences/google/cloud/lifesciences/gapic_version.py +++ b/packages/google-cloud-life-sciences/google/cloud/lifesciences/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.9.8" # {x-release-please-version} +__version__ = "0.9.9" # {x-release-please-version} diff --git a/packages/google-cloud-life-sciences/google/cloud/lifesciences_v2beta/gapic_version.py b/packages/google-cloud-life-sciences/google/cloud/lifesciences_v2beta/gapic_version.py index 766951197b66..301bd68cc9f0 100644 --- a/packages/google-cloud-life-sciences/google/cloud/lifesciences_v2beta/gapic_version.py +++ b/packages/google-cloud-life-sciences/google/cloud/lifesciences_v2beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.9.8" # {x-release-please-version} +__version__ = "0.9.9" # {x-release-please-version} diff --git a/packages/google-cloud-life-sciences/samples/generated_samples/snippet_metadata_google.cloud.lifesciences.v2beta.json b/packages/google-cloud-life-sciences/samples/generated_samples/snippet_metadata_google.cloud.lifesciences.v2beta.json index 9ad16bd489b5..aeaccccee62a 100644 --- a/packages/google-cloud-life-sciences/samples/generated_samples/snippet_metadata_google.cloud.lifesciences.v2beta.json +++ b/packages/google-cloud-life-sciences/samples/generated_samples/snippet_metadata_google.cloud.lifesciences.v2beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-life-sciences", - "version": "0.9.8" + "version": "0.9.9" }, "snippets": [ { diff --git a/packages/google-cloud-life-sciences/setup.py b/packages/google-cloud-life-sciences/setup.py index 8e23e8e516d1..54dddd6c5c90 100644 --- a/packages/google-cloud-life-sciences/setup.py +++ b/packages/google-cloud-life-sciences/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-managed-identities/CHANGELOG.md b/packages/google-cloud-managed-identities/CHANGELOG.md index e3014925bb1e..811a42fec24c 100644 --- a/packages/google-cloud-managed-identities/CHANGELOG.md +++ b/packages/google-cloud-managed-identities/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.9.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-managed-identities-v1.9.2...google-cloud-managed-identities-v1.9.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [1.9.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-managed-identities-v1.9.1...google-cloud-managed-identities-v1.9.2) (2024-02-22) diff --git a/packages/google-cloud-managed-identities/google/cloud/managedidentities/gapic_version.py b/packages/google-cloud-managed-identities/google/cloud/managedidentities/gapic_version.py index f14078b6f555..ec42a8e289c4 100644 --- a/packages/google-cloud-managed-identities/google/cloud/managedidentities/gapic_version.py +++ b/packages/google-cloud-managed-identities/google/cloud/managedidentities/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} diff --git a/packages/google-cloud-managed-identities/google/cloud/managedidentities_v1/gapic_version.py b/packages/google-cloud-managed-identities/google/cloud/managedidentities_v1/gapic_version.py index f14078b6f555..ec42a8e289c4 100644 --- a/packages/google-cloud-managed-identities/google/cloud/managedidentities_v1/gapic_version.py +++ b/packages/google-cloud-managed-identities/google/cloud/managedidentities_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} diff --git a/packages/google-cloud-managed-identities/samples/generated_samples/snippet_metadata_google.cloud.managedidentities.v1.json b/packages/google-cloud-managed-identities/samples/generated_samples/snippet_metadata_google.cloud.managedidentities.v1.json index 38145d2c3367..7c5c56982fe5 100644 --- a/packages/google-cloud-managed-identities/samples/generated_samples/snippet_metadata_google.cloud.managedidentities.v1.json +++ b/packages/google-cloud-managed-identities/samples/generated_samples/snippet_metadata_google.cloud.managedidentities.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-managed-identities", - "version": "1.9.2" + "version": "1.9.3" }, "snippets": [ { diff --git a/packages/google-cloud-managed-identities/setup.py b/packages/google-cloud-managed-identities/setup.py index 652ea0407016..b446fffc6627 100644 --- a/packages/google-cloud-managed-identities/setup.py +++ b/packages/google-cloud-managed-identities/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-media-translation/CHANGELOG.md b/packages/google-cloud-media-translation/CHANGELOG.md index be45e4383c22..a10695aefabb 100644 --- a/packages/google-cloud-media-translation/CHANGELOG.md +++ b/packages/google-cloud-media-translation/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.11.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-media-translation-v0.11.8...google-cloud-media-translation-v0.11.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [0.11.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-media-translation-v0.11.7...google-cloud-media-translation-v0.11.8) (2024-02-22) diff --git a/packages/google-cloud-media-translation/google/cloud/mediatranslation/gapic_version.py b/packages/google-cloud-media-translation/google/cloud/mediatranslation/gapic_version.py index 651274e67675..456019f7dbab 100644 --- a/packages/google-cloud-media-translation/google/cloud/mediatranslation/gapic_version.py +++ b/packages/google-cloud-media-translation/google/cloud/mediatranslation/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.11.8" # {x-release-please-version} +__version__ = "0.11.9" # {x-release-please-version} diff --git a/packages/google-cloud-media-translation/google/cloud/mediatranslation_v1beta1/gapic_version.py b/packages/google-cloud-media-translation/google/cloud/mediatranslation_v1beta1/gapic_version.py index 651274e67675..456019f7dbab 100644 --- a/packages/google-cloud-media-translation/google/cloud/mediatranslation_v1beta1/gapic_version.py +++ b/packages/google-cloud-media-translation/google/cloud/mediatranslation_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.11.8" # {x-release-please-version} +__version__ = "0.11.9" # {x-release-please-version} diff --git a/packages/google-cloud-media-translation/samples/generated_samples/snippet_metadata_google.cloud.mediatranslation.v1beta1.json b/packages/google-cloud-media-translation/samples/generated_samples/snippet_metadata_google.cloud.mediatranslation.v1beta1.json index 9f6c49c5bb6a..cf7543e997d1 100644 --- a/packages/google-cloud-media-translation/samples/generated_samples/snippet_metadata_google.cloud.mediatranslation.v1beta1.json +++ b/packages/google-cloud-media-translation/samples/generated_samples/snippet_metadata_google.cloud.mediatranslation.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-media-translation", - "version": "0.11.8" + "version": "0.11.9" }, "snippets": [ { diff --git a/packages/google-cloud-media-translation/setup.py b/packages/google-cloud-media-translation/setup.py index 73d91f1a590a..92b87499527b 100644 --- a/packages/google-cloud-media-translation/setup.py +++ b/packages/google-cloud-media-translation/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-memcache/CHANGELOG.md b/packages/google-cloud-memcache/CHANGELOG.md index 407009c6d790..0052977f2538 100644 --- a/packages/google-cloud-memcache/CHANGELOG.md +++ b/packages/google-cloud-memcache/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.9.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-memcache-v1.9.2...google-cloud-memcache-v1.9.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [1.9.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-memcache-v1.9.1...google-cloud-memcache-v1.9.2) (2024-02-22) diff --git a/packages/google-cloud-memcache/google/cloud/memcache/gapic_version.py b/packages/google-cloud-memcache/google/cloud/memcache/gapic_version.py index f14078b6f555..ec42a8e289c4 100644 --- a/packages/google-cloud-memcache/google/cloud/memcache/gapic_version.py +++ b/packages/google-cloud-memcache/google/cloud/memcache/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} diff --git a/packages/google-cloud-memcache/google/cloud/memcache_v1/gapic_version.py b/packages/google-cloud-memcache/google/cloud/memcache_v1/gapic_version.py index f14078b6f555..ec42a8e289c4 100644 --- a/packages/google-cloud-memcache/google/cloud/memcache_v1/gapic_version.py +++ b/packages/google-cloud-memcache/google/cloud/memcache_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} diff --git a/packages/google-cloud-memcache/google/cloud/memcache_v1beta2/gapic_version.py b/packages/google-cloud-memcache/google/cloud/memcache_v1beta2/gapic_version.py index f14078b6f555..ec42a8e289c4 100644 --- a/packages/google-cloud-memcache/google/cloud/memcache_v1beta2/gapic_version.py +++ b/packages/google-cloud-memcache/google/cloud/memcache_v1beta2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} diff --git a/packages/google-cloud-memcache/samples/generated_samples/snippet_metadata_google.cloud.memcache.v1.json b/packages/google-cloud-memcache/samples/generated_samples/snippet_metadata_google.cloud.memcache.v1.json index 647179bd662d..77058c7c90af 100644 --- a/packages/google-cloud-memcache/samples/generated_samples/snippet_metadata_google.cloud.memcache.v1.json +++ b/packages/google-cloud-memcache/samples/generated_samples/snippet_metadata_google.cloud.memcache.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-memcache", - "version": "1.9.2" + "version": "1.9.3" }, "snippets": [ { diff --git a/packages/google-cloud-memcache/samples/generated_samples/snippet_metadata_google.cloud.memcache.v1beta2.json b/packages/google-cloud-memcache/samples/generated_samples/snippet_metadata_google.cloud.memcache.v1beta2.json index 152540088c35..841a2540f288 100644 --- a/packages/google-cloud-memcache/samples/generated_samples/snippet_metadata_google.cloud.memcache.v1beta2.json +++ b/packages/google-cloud-memcache/samples/generated_samples/snippet_metadata_google.cloud.memcache.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-memcache", - "version": "1.9.2" + "version": "1.9.3" }, "snippets": [ { diff --git a/packages/google-cloud-memcache/setup.py b/packages/google-cloud-memcache/setup.py index c2d7d5434fe5..3d72086017a1 100644 --- a/packages/google-cloud-memcache/setup.py +++ b/packages/google-cloud-memcache/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-migrationcenter/CHANGELOG.md b/packages/google-cloud-migrationcenter/CHANGELOG.md index 0c42e7f2643f..14fb35cd6d10 100644 --- a/packages/google-cloud-migrationcenter/CHANGELOG.md +++ b/packages/google-cloud-migrationcenter/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-migrationcenter-v0.1.6...google-cloud-migrationcenter-v0.1.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [0.1.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-migrationcenter-v0.1.5...google-cloud-migrationcenter-v0.1.6) (2024-02-22) diff --git a/packages/google-cloud-migrationcenter/google/cloud/migrationcenter/gapic_version.py b/packages/google-cloud-migrationcenter/google/cloud/migrationcenter/gapic_version.py index 60402a4567d1..e34e491c76d0 100644 --- a/packages/google-cloud-migrationcenter/google/cloud/migrationcenter/gapic_version.py +++ b/packages/google-cloud-migrationcenter/google/cloud/migrationcenter/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.6" # {x-release-please-version} +__version__ = "0.1.7" # {x-release-please-version} diff --git a/packages/google-cloud-migrationcenter/google/cloud/migrationcenter_v1/gapic_version.py b/packages/google-cloud-migrationcenter/google/cloud/migrationcenter_v1/gapic_version.py index 60402a4567d1..e34e491c76d0 100644 --- a/packages/google-cloud-migrationcenter/google/cloud/migrationcenter_v1/gapic_version.py +++ b/packages/google-cloud-migrationcenter/google/cloud/migrationcenter_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.6" # {x-release-please-version} +__version__ = "0.1.7" # {x-release-please-version} diff --git a/packages/google-cloud-migrationcenter/samples/generated_samples/snippet_metadata_google.cloud.migrationcenter.v1.json b/packages/google-cloud-migrationcenter/samples/generated_samples/snippet_metadata_google.cloud.migrationcenter.v1.json index 6d3b43a4694c..242b137061c0 100644 --- a/packages/google-cloud-migrationcenter/samples/generated_samples/snippet_metadata_google.cloud.migrationcenter.v1.json +++ b/packages/google-cloud-migrationcenter/samples/generated_samples/snippet_metadata_google.cloud.migrationcenter.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-migrationcenter", - "version": "0.1.6" + "version": "0.1.7" }, "snippets": [ { diff --git a/packages/google-cloud-migrationcenter/setup.py b/packages/google-cloud-migrationcenter/setup.py index d50cc7a4b558..aff20df42d8c 100644 --- a/packages/google-cloud-migrationcenter/setup.py +++ b/packages/google-cloud-migrationcenter/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-monitoring-dashboards/CHANGELOG.md b/packages/google-cloud-monitoring-dashboards/CHANGELOG.md index fd57a1432e85..84636a6a7b48 100644 --- a/packages/google-cloud-monitoring-dashboards/CHANGELOG.md +++ b/packages/google-cloud-monitoring-dashboards/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [2.15.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-monitoring-dashboards-v2.15.0...google-cloud-monitoring-dashboards-v2.15.1) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [2.15.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-monitoring-dashboards-v2.14.1...google-cloud-monitoring-dashboards-v2.15.0) (2024-02-22) diff --git a/packages/google-cloud-monitoring-dashboards/google/cloud/monitoring_dashboard/gapic_version.py b/packages/google-cloud-monitoring-dashboards/google/cloud/monitoring_dashboard/gapic_version.py index 209de14827c9..b3854bf4a586 100644 --- a/packages/google-cloud-monitoring-dashboards/google/cloud/monitoring_dashboard/gapic_version.py +++ b/packages/google-cloud-monitoring-dashboards/google/cloud/monitoring_dashboard/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.15.0" # {x-release-please-version} +__version__ = "2.15.1" # {x-release-please-version} diff --git a/packages/google-cloud-monitoring-dashboards/google/cloud/monitoring_dashboard_v1/gapic_version.py b/packages/google-cloud-monitoring-dashboards/google/cloud/monitoring_dashboard_v1/gapic_version.py index 209de14827c9..b3854bf4a586 100644 --- a/packages/google-cloud-monitoring-dashboards/google/cloud/monitoring_dashboard_v1/gapic_version.py +++ b/packages/google-cloud-monitoring-dashboards/google/cloud/monitoring_dashboard_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.15.0" # {x-release-please-version} +__version__ = "2.15.1" # {x-release-please-version} diff --git a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/gapic_version.py b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/gapic_version.py index 209de14827c9..b3854bf4a586 100644 --- a/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/gapic_version.py +++ b/packages/google-cloud-monitoring-dashboards/google/monitoring/dashboard_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.15.0" # {x-release-please-version} +__version__ = "2.15.1" # {x-release-please-version} diff --git a/packages/google-cloud-monitoring-dashboards/samples/generated_samples/snippet_metadata_google.monitoring.dashboard.v1.json b/packages/google-cloud-monitoring-dashboards/samples/generated_samples/snippet_metadata_google.monitoring.dashboard.v1.json index 50683fd6264b..014e81e0e57e 100644 --- a/packages/google-cloud-monitoring-dashboards/samples/generated_samples/snippet_metadata_google.monitoring.dashboard.v1.json +++ b/packages/google-cloud-monitoring-dashboards/samples/generated_samples/snippet_metadata_google.monitoring.dashboard.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-monitoring-dashboards", - "version": "2.15.0" + "version": "2.15.1" }, "snippets": [ { diff --git a/packages/google-cloud-monitoring-dashboards/setup.py b/packages/google-cloud-monitoring-dashboards/setup.py index 154f2daab5ab..e0b17f193fd2 100644 --- a/packages/google-cloud-monitoring-dashboards/setup.py +++ b/packages/google-cloud-monitoring-dashboards/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-monitoring-metrics-scopes/CHANGELOG.md b/packages/google-cloud-monitoring-metrics-scopes/CHANGELOG.md index 390a5f584efb..c74001b58dfa 100644 --- a/packages/google-cloud-monitoring-metrics-scopes/CHANGELOG.md +++ b/packages/google-cloud-monitoring-metrics-scopes/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.6.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-monitoring-metrics-scopes-v1.6.2...google-cloud-monitoring-metrics-scopes-v1.6.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [1.6.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-monitoring-metrics-scopes-v1.6.1...google-cloud-monitoring-metrics-scopes-v1.6.2) (2024-02-22) diff --git a/packages/google-cloud-monitoring-metrics-scopes/google/cloud/monitoring_metrics_scope/gapic_version.py b/packages/google-cloud-monitoring-metrics-scopes/google/cloud/monitoring_metrics_scope/gapic_version.py index 5a04fdf276c9..fc429472f4c9 100644 --- a/packages/google-cloud-monitoring-metrics-scopes/google/cloud/monitoring_metrics_scope/gapic_version.py +++ b/packages/google-cloud-monitoring-metrics-scopes/google/cloud/monitoring_metrics_scope/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.6.2" # {x-release-please-version} +__version__ = "1.6.3" # {x-release-please-version} diff --git a/packages/google-cloud-monitoring-metrics-scopes/google/cloud/monitoring_metrics_scope_v1/gapic_version.py b/packages/google-cloud-monitoring-metrics-scopes/google/cloud/monitoring_metrics_scope_v1/gapic_version.py index 5a04fdf276c9..fc429472f4c9 100644 --- a/packages/google-cloud-monitoring-metrics-scopes/google/cloud/monitoring_metrics_scope_v1/gapic_version.py +++ b/packages/google-cloud-monitoring-metrics-scopes/google/cloud/monitoring_metrics_scope_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.6.2" # {x-release-please-version} +__version__ = "1.6.3" # {x-release-please-version} diff --git a/packages/google-cloud-monitoring-metrics-scopes/samples/generated_samples/snippet_metadata_google.monitoring.metricsscope.v1.json b/packages/google-cloud-monitoring-metrics-scopes/samples/generated_samples/snippet_metadata_google.monitoring.metricsscope.v1.json index 22f3d55f2e98..adae431134cd 100644 --- a/packages/google-cloud-monitoring-metrics-scopes/samples/generated_samples/snippet_metadata_google.monitoring.metricsscope.v1.json +++ b/packages/google-cloud-monitoring-metrics-scopes/samples/generated_samples/snippet_metadata_google.monitoring.metricsscope.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-monitoring-metrics-scopes", - "version": "1.6.2" + "version": "1.6.3" }, "snippets": [ { diff --git a/packages/google-cloud-monitoring-metrics-scopes/setup.py b/packages/google-cloud-monitoring-metrics-scopes/setup.py index a964da7e783b..e8ff159febf3 100644 --- a/packages/google-cloud-monitoring-metrics-scopes/setup.py +++ b/packages/google-cloud-monitoring-metrics-scopes/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-monitoring/CHANGELOG.md b/packages/google-cloud-monitoring/CHANGELOG.md index c811008be000..d13d266b89ca 100644 --- a/packages/google-cloud-monitoring/CHANGELOG.md +++ b/packages/google-cloud-monitoring/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-monitoring/#history +## [2.19.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-monitoring-v2.19.2...google-cloud-monitoring-v2.19.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [2.19.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-monitoring-v2.19.1...google-cloud-monitoring-v2.19.2) (2024-02-22) diff --git a/packages/google-cloud-monitoring/google/cloud/monitoring/gapic_version.py b/packages/google-cloud-monitoring/google/cloud/monitoring/gapic_version.py index d7d651d41589..d97c3bed2acd 100644 --- a/packages/google-cloud-monitoring/google/cloud/monitoring/gapic_version.py +++ b/packages/google-cloud-monitoring/google/cloud/monitoring/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.19.2" # {x-release-please-version} +__version__ = "2.19.3" # {x-release-please-version} diff --git a/packages/google-cloud-monitoring/google/cloud/monitoring_v3/gapic_version.py b/packages/google-cloud-monitoring/google/cloud/monitoring_v3/gapic_version.py index d7d651d41589..d97c3bed2acd 100644 --- a/packages/google-cloud-monitoring/google/cloud/monitoring_v3/gapic_version.py +++ b/packages/google-cloud-monitoring/google/cloud/monitoring_v3/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.19.2" # {x-release-please-version} +__version__ = "2.19.3" # {x-release-please-version} diff --git a/packages/google-cloud-monitoring/samples/generated_samples/snippet_metadata_google.monitoring.v3.json b/packages/google-cloud-monitoring/samples/generated_samples/snippet_metadata_google.monitoring.v3.json index b3f55f06c3c6..eefaef3b9914 100644 --- a/packages/google-cloud-monitoring/samples/generated_samples/snippet_metadata_google.monitoring.v3.json +++ b/packages/google-cloud-monitoring/samples/generated_samples/snippet_metadata_google.monitoring.v3.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-monitoring", - "version": "2.19.2" + "version": "2.19.3" }, "snippets": [ { diff --git a/packages/google-cloud-monitoring/setup.py b/packages/google-cloud-monitoring/setup.py index 29fe47b760b7..337936f6b2ac 100644 --- a/packages/google-cloud-monitoring/setup.py +++ b/packages/google-cloud-monitoring/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-netapp/CHANGELOG.md b/packages/google-cloud-netapp/CHANGELOG.md index 97597a48d160..bcd16f62eb7c 100644 --- a/packages/google-cloud-netapp/CHANGELOG.md +++ b/packages/google-cloud-netapp/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.3.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-netapp-v0.3.6...google-cloud-netapp-v0.3.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [0.3.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-netapp-v0.3.5...google-cloud-netapp-v0.3.6) (2024-02-22) diff --git a/packages/google-cloud-netapp/google/cloud/netapp/gapic_version.py b/packages/google-cloud-netapp/google/cloud/netapp/gapic_version.py index dca6dc837e67..91090a840535 100644 --- a/packages/google-cloud-netapp/google/cloud/netapp/gapic_version.py +++ b/packages/google-cloud-netapp/google/cloud/netapp/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.6" # {x-release-please-version} +__version__ = "0.3.7" # {x-release-please-version} diff --git a/packages/google-cloud-netapp/google/cloud/netapp_v1/gapic_version.py b/packages/google-cloud-netapp/google/cloud/netapp_v1/gapic_version.py index dca6dc837e67..91090a840535 100644 --- a/packages/google-cloud-netapp/google/cloud/netapp_v1/gapic_version.py +++ b/packages/google-cloud-netapp/google/cloud/netapp_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.6" # {x-release-please-version} +__version__ = "0.3.7" # {x-release-please-version} diff --git a/packages/google-cloud-netapp/samples/generated_samples/snippet_metadata_google.cloud.netapp.v1.json b/packages/google-cloud-netapp/samples/generated_samples/snippet_metadata_google.cloud.netapp.v1.json index fdc2149d8a44..28809ac96e4e 100644 --- a/packages/google-cloud-netapp/samples/generated_samples/snippet_metadata_google.cloud.netapp.v1.json +++ b/packages/google-cloud-netapp/samples/generated_samples/snippet_metadata_google.cloud.netapp.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-netapp", - "version": "0.3.6" + "version": "0.3.7" }, "snippets": [ { diff --git a/packages/google-cloud-netapp/setup.py b/packages/google-cloud-netapp/setup.py index 05e51afa7599..935fb34f995a 100644 --- a/packages/google-cloud-netapp/setup.py +++ b/packages/google-cloud-netapp/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-network-connectivity/CHANGELOG.md b/packages/google-cloud-network-connectivity/CHANGELOG.md index 4bd679a112d7..b0d22a615cad 100644 --- a/packages/google-cloud-network-connectivity/CHANGELOG.md +++ b/packages/google-cloud-network-connectivity/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [2.4.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-network-connectivity-v2.4.2...google-cloud-network-connectivity-v2.4.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [2.4.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-network-connectivity-v2.4.1...google-cloud-network-connectivity-v2.4.2) (2024-02-22) diff --git a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity/gapic_version.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity/gapic_version.py index 29d5105286a3..93733bcfd3b9 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity/gapic_version.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.4.2" # {x-release-please-version} +__version__ = "2.4.3" # {x-release-please-version} diff --git a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/gapic_version.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/gapic_version.py index 29d5105286a3..93733bcfd3b9 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/gapic_version.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.4.2" # {x-release-please-version} +__version__ = "2.4.3" # {x-release-please-version} diff --git a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1alpha1/gapic_version.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1alpha1/gapic_version.py index 29d5105286a3..93733bcfd3b9 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1alpha1/gapic_version.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1alpha1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.4.2" # {x-release-please-version} +__version__ = "2.4.3" # {x-release-please-version} diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1.json b/packages/google-cloud-network-connectivity/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1.json index e5f1fda4a1dd..24b3abdf3bc8 100644 --- a/packages/google-cloud-network-connectivity/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1.json +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-network-connectivity", - "version": "2.4.2" + "version": "2.4.3" }, "snippets": [ { diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1alpha1.json b/packages/google-cloud-network-connectivity/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1alpha1.json index 82741a131873..2454938cf089 100644 --- a/packages/google-cloud-network-connectivity/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1alpha1.json +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1alpha1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-network-connectivity", - "version": "2.4.2" + "version": "2.4.3" }, "snippets": [ { diff --git a/packages/google-cloud-network-connectivity/setup.py b/packages/google-cloud-network-connectivity/setup.py index d05281aa9500..a988af9a9641 100644 --- a/packages/google-cloud-network-connectivity/setup.py +++ b/packages/google-cloud-network-connectivity/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-network-management/CHANGELOG.md b/packages/google-cloud-network-management/CHANGELOG.md index 3ba166f6c03b..26f3aeb2bc4e 100644 --- a/packages/google-cloud-network-management/CHANGELOG.md +++ b/packages/google-cloud-network-management/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.13.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-network-management-v1.13.2...google-cloud-network-management-v1.13.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12385](https://github.com/googleapis/google-cloud-python/issues/12385)) ([d50f4d0](https://github.com/googleapis/google-cloud-python/commit/d50f4d042774e2f12e9fe03459eae9ce91247df3)) + ## [1.13.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-network-management-v1.13.1...google-cloud-network-management-v1.13.2) (2024-02-22) diff --git a/packages/google-cloud-network-management/google/cloud/network_management/gapic_version.py b/packages/google-cloud-network-management/google/cloud/network_management/gapic_version.py index 3434b217efee..40e034931fac 100644 --- a/packages/google-cloud-network-management/google/cloud/network_management/gapic_version.py +++ b/packages/google-cloud-network-management/google/cloud/network_management/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.13.2" # {x-release-please-version} +__version__ = "1.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-network-management/google/cloud/network_management_v1/gapic_version.py b/packages/google-cloud-network-management/google/cloud/network_management_v1/gapic_version.py index 3434b217efee..40e034931fac 100644 --- a/packages/google-cloud-network-management/google/cloud/network_management_v1/gapic_version.py +++ b/packages/google-cloud-network-management/google/cloud/network_management_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.2" # {x-release-please-version} +__version__ = "1.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-network-management/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json b/packages/google-cloud-network-management/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json index 4a00ed0d5e9b..0d7718bb23cf 100644 --- a/packages/google-cloud-network-management/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json +++ b/packages/google-cloud-network-management/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-network-management", - "version": "1.13.2" + "version": "1.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-network-management/setup.py b/packages/google-cloud-network-management/setup.py index 59408fcff662..e0f919540bcf 100644 --- a/packages/google-cloud-network-management/setup.py +++ b/packages/google-cloud-network-management/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-network-security/CHANGELOG.md b/packages/google-cloud-network-security/CHANGELOG.md index 95389c0928d9..1c982ab669c1 100644 --- a/packages/google-cloud-network-security/CHANGELOG.md +++ b/packages/google-cloud-network-security/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.9.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-network-security-v0.9.8...google-cloud-network-security-v0.9.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [0.9.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-network-security-v0.9.7...google-cloud-network-security-v0.9.8) (2024-02-22) diff --git a/packages/google-cloud-network-security/google/cloud/network_security/gapic_version.py b/packages/google-cloud-network-security/google/cloud/network_security/gapic_version.py index 766951197b66..301bd68cc9f0 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security/gapic_version.py +++ b/packages/google-cloud-network-security/google/cloud/network_security/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.9.8" # {x-release-please-version} +__version__ = "0.9.9" # {x-release-please-version} diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/gapic_version.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/gapic_version.py index 766951197b66..301bd68cc9f0 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/gapic_version.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.9.8" # {x-release-please-version} +__version__ = "0.9.9" # {x-release-please-version} diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/gapic_version.py b/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/gapic_version.py index 766951197b66..301bd68cc9f0 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/gapic_version.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.9.8" # {x-release-please-version} +__version__ = "0.9.9" # {x-release-please-version} diff --git a/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json b/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json index faacfc9322aa..9b1c591b9b02 100644 --- a/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json +++ b/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-network-security", - "version": "0.9.8" + "version": "0.9.9" }, "snippets": [ { diff --git a/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json b/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json index f67388ab22a2..99995b3647fe 100644 --- a/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json +++ b/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-network-security", - "version": "0.9.8" + "version": "0.9.9" }, "snippets": [ { diff --git a/packages/google-cloud-network-security/setup.py b/packages/google-cloud-network-security/setup.py index 964aa92c6682..669db4728545 100644 --- a/packages/google-cloud-network-security/setup.py +++ b/packages/google-cloud-network-security/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-network-services/CHANGELOG.md b/packages/google-cloud-network-services/CHANGELOG.md index 189850421d8e..4edad41f1b36 100644 --- a/packages/google-cloud-network-services/CHANGELOG.md +++ b/packages/google-cloud-network-services/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.5.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-network-services-v0.5.8...google-cloud-network-services-v0.5.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [0.5.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-network-services-v0.5.7...google-cloud-network-services-v0.5.8) (2024-02-22) diff --git a/packages/google-cloud-network-services/google/cloud/network_services/gapic_version.py b/packages/google-cloud-network-services/google/cloud/network_services/gapic_version.py index 09f1bfa9ad82..f4186fc1a151 100644 --- a/packages/google-cloud-network-services/google/cloud/network_services/gapic_version.py +++ b/packages/google-cloud-network-services/google/cloud/network_services/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.8" # {x-release-please-version} +__version__ = "0.5.9" # {x-release-please-version} diff --git a/packages/google-cloud-network-services/google/cloud/network_services_v1/gapic_version.py b/packages/google-cloud-network-services/google/cloud/network_services_v1/gapic_version.py index 09f1bfa9ad82..f4186fc1a151 100644 --- a/packages/google-cloud-network-services/google/cloud/network_services_v1/gapic_version.py +++ b/packages/google-cloud-network-services/google/cloud/network_services_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.8" # {x-release-please-version} +__version__ = "0.5.9" # {x-release-please-version} diff --git a/packages/google-cloud-network-services/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json b/packages/google-cloud-network-services/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json index ff4a21962e1b..add61944f8e5 100644 --- a/packages/google-cloud-network-services/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json +++ b/packages/google-cloud-network-services/samples/generated_samples/snippet_metadata_google.cloud.networkservices.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-network-services", - "version": "0.5.8" + "version": "0.5.9" }, "snippets": [ { diff --git a/packages/google-cloud-network-services/setup.py b/packages/google-cloud-network-services/setup.py index 4dc23b2a9f58..1a69fd09652f 100644 --- a/packages/google-cloud-network-services/setup.py +++ b/packages/google-cloud-network-services/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-notebooks/CHANGELOG.md b/packages/google-cloud-notebooks/CHANGELOG.md index 3e20cdc5ee12..a8644f8e97ab 100644 --- a/packages/google-cloud-notebooks/CHANGELOG.md +++ b/packages/google-cloud-notebooks/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.10.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-notebooks-v1.10.2...google-cloud-notebooks-v1.10.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [1.10.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-notebooks-v1.10.1...google-cloud-notebooks-v1.10.2) (2024-02-22) diff --git a/packages/google-cloud-notebooks/google/cloud/notebooks/gapic_version.py b/packages/google-cloud-notebooks/google/cloud/notebooks/gapic_version.py index 7a033a50e6cd..d74c07c1961e 100644 --- a/packages/google-cloud-notebooks/google/cloud/notebooks/gapic_version.py +++ b/packages/google-cloud-notebooks/google/cloud/notebooks/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.2" # {x-release-please-version} +__version__ = "1.10.3" # {x-release-please-version} diff --git a/packages/google-cloud-notebooks/google/cloud/notebooks_v1/gapic_version.py b/packages/google-cloud-notebooks/google/cloud/notebooks_v1/gapic_version.py index 7a033a50e6cd..d74c07c1961e 100644 --- a/packages/google-cloud-notebooks/google/cloud/notebooks_v1/gapic_version.py +++ b/packages/google-cloud-notebooks/google/cloud/notebooks_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.2" # {x-release-please-version} +__version__ = "1.10.3" # {x-release-please-version} diff --git a/packages/google-cloud-notebooks/google/cloud/notebooks_v1beta1/gapic_version.py b/packages/google-cloud-notebooks/google/cloud/notebooks_v1beta1/gapic_version.py index 7a033a50e6cd..d74c07c1961e 100644 --- a/packages/google-cloud-notebooks/google/cloud/notebooks_v1beta1/gapic_version.py +++ b/packages/google-cloud-notebooks/google/cloud/notebooks_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.2" # {x-release-please-version} +__version__ = "1.10.3" # {x-release-please-version} diff --git a/packages/google-cloud-notebooks/google/cloud/notebooks_v2/gapic_version.py b/packages/google-cloud-notebooks/google/cloud/notebooks_v2/gapic_version.py index 7a033a50e6cd..d74c07c1961e 100644 --- a/packages/google-cloud-notebooks/google/cloud/notebooks_v2/gapic_version.py +++ b/packages/google-cloud-notebooks/google/cloud/notebooks_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.2" # {x-release-please-version} +__version__ = "1.10.3" # {x-release-please-version} diff --git a/packages/google-cloud-notebooks/samples/generated_samples/snippet_metadata_google.cloud.notebooks.v1.json b/packages/google-cloud-notebooks/samples/generated_samples/snippet_metadata_google.cloud.notebooks.v1.json index 99477fc8ab57..41657c98bb50 100644 --- a/packages/google-cloud-notebooks/samples/generated_samples/snippet_metadata_google.cloud.notebooks.v1.json +++ b/packages/google-cloud-notebooks/samples/generated_samples/snippet_metadata_google.cloud.notebooks.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-notebooks", - "version": "1.10.2" + "version": "1.10.3" }, "snippets": [ { diff --git a/packages/google-cloud-notebooks/samples/generated_samples/snippet_metadata_google.cloud.notebooks.v1beta1.json b/packages/google-cloud-notebooks/samples/generated_samples/snippet_metadata_google.cloud.notebooks.v1beta1.json index aec297d32138..6361580f9206 100644 --- a/packages/google-cloud-notebooks/samples/generated_samples/snippet_metadata_google.cloud.notebooks.v1beta1.json +++ b/packages/google-cloud-notebooks/samples/generated_samples/snippet_metadata_google.cloud.notebooks.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-notebooks", - "version": "1.10.2" + "version": "1.10.3" }, "snippets": [ { diff --git a/packages/google-cloud-notebooks/samples/generated_samples/snippet_metadata_google.cloud.notebooks.v2.json b/packages/google-cloud-notebooks/samples/generated_samples/snippet_metadata_google.cloud.notebooks.v2.json index 05a2183ff6a9..f72e5dea5df6 100644 --- a/packages/google-cloud-notebooks/samples/generated_samples/snippet_metadata_google.cloud.notebooks.v2.json +++ b/packages/google-cloud-notebooks/samples/generated_samples/snippet_metadata_google.cloud.notebooks.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-notebooks", - "version": "1.10.2" + "version": "1.10.3" }, "snippets": [ { diff --git a/packages/google-cloud-notebooks/setup.py b/packages/google-cloud-notebooks/setup.py index d974b076f584..6ecfd03262a9 100644 --- a/packages/google-cloud-notebooks/setup.py +++ b/packages/google-cloud-notebooks/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-optimization/CHANGELOG.md b/packages/google-cloud-optimization/CHANGELOG.md index 45cd2d8f2b4f..cc1ca71a4dfe 100644 --- a/packages/google-cloud-optimization/CHANGELOG.md +++ b/packages/google-cloud-optimization/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.8.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-optimization-v1.8.2...google-cloud-optimization-v1.8.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [1.8.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-optimization-v1.8.1...google-cloud-optimization-v1.8.2) (2024-02-22) diff --git a/packages/google-cloud-optimization/google/cloud/optimization/gapic_version.py b/packages/google-cloud-optimization/google/cloud/optimization/gapic_version.py index 0b81cd44c284..f9e85c87b4d6 100644 --- a/packages/google-cloud-optimization/google/cloud/optimization/gapic_version.py +++ b/packages/google-cloud-optimization/google/cloud/optimization/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.8.2" # {x-release-please-version} +__version__ = "1.8.3" # {x-release-please-version} diff --git a/packages/google-cloud-optimization/google/cloud/optimization_v1/gapic_version.py b/packages/google-cloud-optimization/google/cloud/optimization_v1/gapic_version.py index 0b81cd44c284..f9e85c87b4d6 100644 --- a/packages/google-cloud-optimization/google/cloud/optimization_v1/gapic_version.py +++ b/packages/google-cloud-optimization/google/cloud/optimization_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.2" # {x-release-please-version} +__version__ = "1.8.3" # {x-release-please-version} diff --git a/packages/google-cloud-optimization/samples/generated_samples/snippet_metadata_google.cloud.optimization.v1.json b/packages/google-cloud-optimization/samples/generated_samples/snippet_metadata_google.cloud.optimization.v1.json index 87ef0fede36a..3389a186db94 100644 --- a/packages/google-cloud-optimization/samples/generated_samples/snippet_metadata_google.cloud.optimization.v1.json +++ b/packages/google-cloud-optimization/samples/generated_samples/snippet_metadata_google.cloud.optimization.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-optimization", - "version": "1.8.2" + "version": "1.8.3" }, "snippets": [ { diff --git a/packages/google-cloud-optimization/setup.py b/packages/google-cloud-optimization/setup.py index 45b410eb9c4d..8bfc78d2db4f 100644 --- a/packages/google-cloud-optimization/setup.py +++ b/packages/google-cloud-optimization/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-orchestration-airflow/CHANGELOG.md b/packages/google-cloud-orchestration-airflow/CHANGELOG.md index 09613da707c1..05ab188bab4b 100644 --- a/packages/google-cloud-orchestration-airflow/CHANGELOG.md +++ b/packages/google-cloud-orchestration-airflow/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.12.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-orchestration-airflow-v1.12.0...google-cloud-orchestration-airflow-v1.12.1) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [1.12.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-orchestration-airflow-v1.11.1...google-cloud-orchestration-airflow-v1.12.0) (2024-02-22) diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service/gapic_version.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service/gapic_version.py index 18a7732658ee..ac3bc60c3fb3 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service/gapic_version.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service/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-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/gapic_version.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/gapic_version.py index 18a7732658ee..ac3bc60c3fb3 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/gapic_version.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_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-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/gapic_version.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/gapic_version.py index 18a7732658ee..ac3bc60c3fb3 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/gapic_version.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/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-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json b/packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json index d41fd9b5919c..7708601e44ce 100644 --- a/packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json +++ b/packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-orchestration-airflow", - "version": "1.12.0" + "version": "1.12.1" }, "snippets": [ { diff --git a/packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json b/packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json index 4441fb389ea7..29964ae57f78 100644 --- a/packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json +++ b/packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-orchestration-airflow-service", - "version": "1.12.0" + "version": "1.12.1" }, "snippets": [ { diff --git a/packages/google-cloud-orchestration-airflow/setup.py b/packages/google-cloud-orchestration-airflow/setup.py index 3ff795a6266e..cf3fdfd928f7 100644 --- a/packages/google-cloud-orchestration-airflow/setup.py +++ b/packages/google-cloud-orchestration-airflow/setup.py @@ -44,7 +44,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-os-config/CHANGELOG.md b/packages/google-cloud-os-config/CHANGELOG.md index 0536dd03a5b3..6e956b568cdd 100644 --- a/packages/google-cloud-os-config/CHANGELOG.md +++ b/packages/google-cloud-os-config/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.17.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-os-config-v1.17.2...google-cloud-os-config-v1.17.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [1.17.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-os-config-v1.17.1...google-cloud-os-config-v1.17.2) (2024-02-22) diff --git a/packages/google-cloud-os-config/google/cloud/osconfig/gapic_version.py b/packages/google-cloud-os-config/google/cloud/osconfig/gapic_version.py index 1e0921955b0c..3639317ee4f0 100644 --- a/packages/google-cloud-os-config/google/cloud/osconfig/gapic_version.py +++ b/packages/google-cloud-os-config/google/cloud/osconfig/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.17.2" # {x-release-please-version} +__version__ = "1.17.3" # {x-release-please-version} diff --git a/packages/google-cloud-os-config/google/cloud/osconfig_v1/gapic_version.py b/packages/google-cloud-os-config/google/cloud/osconfig_v1/gapic_version.py index 1e0921955b0c..3639317ee4f0 100644 --- a/packages/google-cloud-os-config/google/cloud/osconfig_v1/gapic_version.py +++ b/packages/google-cloud-os-config/google/cloud/osconfig_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.17.2" # {x-release-please-version} +__version__ = "1.17.3" # {x-release-please-version} diff --git a/packages/google-cloud-os-config/google/cloud/osconfig_v1alpha/gapic_version.py b/packages/google-cloud-os-config/google/cloud/osconfig_v1alpha/gapic_version.py index 1e0921955b0c..3639317ee4f0 100644 --- a/packages/google-cloud-os-config/google/cloud/osconfig_v1alpha/gapic_version.py +++ b/packages/google-cloud-os-config/google/cloud/osconfig_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.17.2" # {x-release-please-version} +__version__ = "1.17.3" # {x-release-please-version} diff --git a/packages/google-cloud-os-config/samples/generated_samples/snippet_metadata_google.cloud.osconfig.v1.json b/packages/google-cloud-os-config/samples/generated_samples/snippet_metadata_google.cloud.osconfig.v1.json index a21fe7c2ef23..cf07b71965c9 100644 --- a/packages/google-cloud-os-config/samples/generated_samples/snippet_metadata_google.cloud.osconfig.v1.json +++ b/packages/google-cloud-os-config/samples/generated_samples/snippet_metadata_google.cloud.osconfig.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-os-config", - "version": "1.17.2" + "version": "1.17.3" }, "snippets": [ { diff --git a/packages/google-cloud-os-config/samples/generated_samples/snippet_metadata_google.cloud.osconfig.v1alpha.json b/packages/google-cloud-os-config/samples/generated_samples/snippet_metadata_google.cloud.osconfig.v1alpha.json index 0b9efb897244..a26583a9e173 100644 --- a/packages/google-cloud-os-config/samples/generated_samples/snippet_metadata_google.cloud.osconfig.v1alpha.json +++ b/packages/google-cloud-os-config/samples/generated_samples/snippet_metadata_google.cloud.osconfig.v1alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-os-config", - "version": "1.17.2" + "version": "1.17.3" }, "snippets": [ { diff --git a/packages/google-cloud-os-config/setup.py b/packages/google-cloud-os-config/setup.py index 09a3cba161e6..4aac968542ed 100644 --- a/packages/google-cloud-os-config/setup.py +++ b/packages/google-cloud-os-config/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-os-login/CHANGELOG.md b/packages/google-cloud-os-login/CHANGELOG.md index 60e1c07ebd42..6c48623c6d01 100644 --- a/packages/google-cloud-os-login/CHANGELOG.md +++ b/packages/google-cloud-os-login/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-oslogin/#history +## [2.14.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-os-login-v2.14.2...google-cloud-os-login-v2.14.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [2.14.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-os-login-v2.14.1...google-cloud-os-login-v2.14.2) (2024-02-22) diff --git a/packages/google-cloud-os-login/google/cloud/oslogin/gapic_version.py b/packages/google-cloud-os-login/google/cloud/oslogin/gapic_version.py index e00709b42b8e..6440b3563e45 100644 --- a/packages/google-cloud-os-login/google/cloud/oslogin/gapic_version.py +++ b/packages/google-cloud-os-login/google/cloud/oslogin/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.14.2" # {x-release-please-version} +__version__ = "2.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic_version.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic_version.py index e00709b42b8e..6440b3563e45 100644 --- a/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic_version.py +++ b/packages/google-cloud-os-login/google/cloud/oslogin_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.2" # {x-release-please-version} +__version__ = "2.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-os-login/samples/generated_samples/snippet_metadata_google.cloud.oslogin.v1.json b/packages/google-cloud-os-login/samples/generated_samples/snippet_metadata_google.cloud.oslogin.v1.json index fe96553145f6..3300dcae4177 100644 --- a/packages/google-cloud-os-login/samples/generated_samples/snippet_metadata_google.cloud.oslogin.v1.json +++ b/packages/google-cloud-os-login/samples/generated_samples/snippet_metadata_google.cloud.oslogin.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-os-login", - "version": "2.14.2" + "version": "2.14.3" }, "snippets": [ { diff --git a/packages/google-cloud-os-login/setup.py b/packages/google-cloud-os-login/setup.py index fd390c737689..75739bef38d2 100644 --- a/packages/google-cloud-os-login/setup.py +++ b/packages/google-cloud-os-login/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-parallelstore/.OwlBot.yaml b/packages/google-cloud-parallelstore/.OwlBot.yaml new file mode 100644 index 000000000000..a6f6dd5d55da --- /dev/null +++ b/packages/google-cloud-parallelstore/.OwlBot.yaml @@ -0,0 +1,18 @@ +# Copyright 2022 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. + +deep-copy-regex: + - source: /google/cloud/parallelstore/(v.*)/.*-py + dest: /owl-bot-staging/google-cloud-parallelstore/$1 +api-name: google-cloud-parallelstore diff --git a/packages/google-cloud-parallelstore/.coveragerc b/packages/google-cloud-parallelstore/.coveragerc new file mode 100644 index 000000000000..18ae9360538f --- /dev/null +++ b/packages/google-cloud-parallelstore/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/parallelstore/__init__.py + google/cloud/parallelstore/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/packages/google-cloud-parallelstore/.flake8 b/packages/google-cloud-parallelstore/.flake8 new file mode 100644 index 000000000000..87f6e408c47d --- /dev/null +++ b/packages/google-cloud-parallelstore/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2023 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 +# +# https://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 by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E231, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/packages/google-cloud-parallelstore/.gitignore b/packages/google-cloud-parallelstore/.gitignore new file mode 100644 index 000000000000..b4243ced74e4 --- /dev/null +++ b/packages/google-cloud-parallelstore/.gitignore @@ -0,0 +1,63 @@ +*.py[cod] +*.sw[op] + +# C extensions +*.so + +# Packages +*.egg +*.egg-info +dist +build +eggs +.eggs +parts +bin +var +sdist +develop-eggs +.installed.cfg +lib +lib64 +__pycache__ + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.nox +.cache +.pytest_cache + + +# Mac +.DS_Store + +# JetBrains +.idea + +# VS Code +.vscode + +# emacs +*~ + +# Built documentation +docs/_build +bigquery/docs/generated +docs.metadata + +# Virtual environment +env/ + +# Test logs +coverage.xml +*sponge_log.xml + +# System test environment variables. +system_tests/local_test_setup + +# Make sure a generated file isn't accidentally committed. +pylintrc +pylintrc.test diff --git a/packages/google-cloud-parallelstore/.repo-metadata.json b/packages/google-cloud-parallelstore/.repo-metadata.json new file mode 100644 index 000000000000..9ac7dfe0db3d --- /dev/null +++ b/packages/google-cloud-parallelstore/.repo-metadata.json @@ -0,0 +1,17 @@ +{ + "name": "google-cloud-parallelstore", + "name_pretty": "Parallelstore API", + "api_description": "Parallelstore is based on Intel DAOS and delivers up to 6.3x greater read throughput performance compared to competitive Lustre scratch offerings.", + "product_documentation": "https://cloud.google.com/parallelstore", + "client_documentation": "https://cloud.google.com/python/docs/reference/google-cloud-parallelstore/latest", + "issue_tracker": "https://github.com/googleapis/google-cloud-python/issues", + "release_level": "preview", + "language": "python", + "library_type": "GAPIC_AUTO", + "repo": "googleapis/google-cloud-python", + "distribution_name": "google-cloud-parallelstore", + "api_id": "parallelstore.googleapis.com", + "default_version": "v1beta", + "codeowner_team": "", + "api_shortname": "parallelstore" +} diff --git a/packages/google-cloud-parallelstore/CHANGELOG.md b/packages/google-cloud-parallelstore/CHANGELOG.md new file mode 100644 index 000000000000..75428d01d82d --- /dev/null +++ b/packages/google-cloud-parallelstore/CHANGELOG.md @@ -0,0 +1,17 @@ +# Changelog + +## [0.1.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-parallelstore-v0.1.0...google-cloud-parallelstore-v0.1.1) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + +## 0.1.0 (2024-03-04) + + +### Features + +* add initial files for google.cloud.parallelstore.v1beta ([#12368](https://github.com/googleapis/google-cloud-python/issues/12368)) ([db14111](https://github.com/googleapis/google-cloud-python/commit/db1411133fbdd2ee333aca125dd05996c7a95f59)) + +## Changelog diff --git a/packages/google-cloud-parallelstore/CODE_OF_CONDUCT.md b/packages/google-cloud-parallelstore/CODE_OF_CONDUCT.md new file mode 100644 index 000000000000..039f43681204 --- /dev/null +++ b/packages/google-cloud-parallelstore/CODE_OF_CONDUCT.md @@ -0,0 +1,95 @@ + +# Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of +experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, or to ban temporarily or permanently any +contributor for other behaviors that they deem inappropriate, threatening, +offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +This Code of Conduct also applies outside the project spaces when the Project +Steward has a reasonable belief that an individual's behavior may have a +negative impact on the project or its community. + +## Conflict Resolution + +We do not believe that all conflict is bad; healthy debate and disagreement +often yield positive results. However, it is never okay to be disrespectful or +to engage in behavior that violates the project’s code of conduct. + +If you see someone violating the code of conduct, you are encouraged to address +the behavior directly with those involved. Many issues can be resolved quickly +and easily, and this gives people more control over the outcome of their +dispute. If you are unable to resolve the matter for any reason, or if the +behavior is threatening or harassing, report it. We are dedicated to providing +an environment where participants feel welcome and safe. + + +Reports should be directed to *googleapis-stewards@google.com*, the +Project Steward(s) for *Google Cloud Client Libraries*. It is the Project Steward’s duty to +receive and address reported violations of the code of conduct. They will then +work with a committee consisting of representatives from the Open Source +Programs Office and the Google Open Source Strategy team. If for any reason you +are uncomfortable reaching out to the Project Steward, please email +opensource@google.com. + +We will investigate every complaint, but you may not receive a direct response. +We will use our discretion in determining when and how to follow up on reported +incidents, which may range from not taking action to permanent expulsion from +the project and project-sponsored spaces. We will notify the accused of the +report and provide them an opportunity to discuss it before any action is taken. +The identity of the reporter will be omitted from the details of the report +supplied to the accused. In potentially harmful situations, such as ongoing +harassment or threats to anyone's safety, we may take action without notice. + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 1.4, +available at +https://www.contributor-covenant.org/version/1/4/code-of-conduct.html \ No newline at end of file diff --git a/packages/google-cloud-parallelstore/CONTRIBUTING.rst b/packages/google-cloud-parallelstore/CONTRIBUTING.rst new file mode 100644 index 000000000000..7ccb06b1d947 --- /dev/null +++ b/packages/google-cloud-parallelstore/CONTRIBUTING.rst @@ -0,0 +1,271 @@ +.. Generated by synthtool. DO NOT EDIT! +############ +Contributing +############ + +#. **Please sign one of the contributor license agreements below.** +#. Fork the repo, develop and test your code changes, add docs. +#. Make sure that your commit messages clearly describe the changes. +#. Send a pull request. (Please Read: `Faster Pull Request Reviews`_) + +.. _Faster Pull Request Reviews: https://github.com/kubernetes/community/blob/master/contributors/guide/pull-requests.md#best-practices-for-faster-reviews + +.. contents:: Here are some guidelines for hacking on the Google Cloud Client libraries. + +*************** +Adding Features +*************** + +In order to add a feature: + +- The feature must be documented in both the API and narrative + documentation. + +- The feature must work fully on the following CPython versions: + 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + +- The feature must not add unnecessary dependencies (where + "unnecessary" is of course subjective, but new dependencies should + be discussed). + +**************************** +Using a Development Checkout +**************************** + +You'll have to create a development environment using a Git checkout: + +- While logged into your GitHub account, navigate to the + ``google-cloud-python`` `repo`_ on GitHub. + +- Fork and clone the ``google-cloud-python`` repository to your GitHub account by + clicking the "Fork" button. + +- Clone your fork of ``google-cloud-python`` from your GitHub account to your local + computer, substituting your account username and specifying the destination + as ``hack-on-google-cloud-python``. E.g.:: + + $ cd ${HOME} + $ git clone git@github.com:USERNAME/google-cloud-python.git hack-on-google-cloud-python + $ cd hack-on-google-cloud-python + # Configure remotes such that you can pull changes from the googleapis/google-cloud-python + # repository into your local repository. + $ git remote add upstream git@github.com:googleapis/google-cloud-python.git + # fetch and merge changes from upstream into main + $ git fetch upstream + $ git merge upstream/main + +Now your local repo is set up such that you will push changes to your GitHub +repo, from which you can submit a pull request. + +To work on the codebase and run the tests, we recommend using ``nox``, +but you can also use a ``virtualenv`` of your own creation. + +.. _repo: https://github.com/googleapis/google-cloud-python + +Using ``nox`` +============= + +We use `nox `__ to instrument our tests. + +- To test your changes, run unit tests with ``nox``:: + $ nox -s unit + +- To run a single unit test:: + + $ nox -s unit-3.12 -- -k + + + .. note:: + + The unit tests and system tests are described in the + ``noxfile.py`` files in each directory. + +.. nox: https://pypi.org/project/nox/ + +***************************************** +I'm getting weird errors... Can you help? +***************************************** + +If the error mentions ``Python.h`` not being found, +install ``python-dev`` and try again. +On Debian/Ubuntu:: + + $ sudo apt-get install python-dev + +************ +Coding Style +************ +- We use the automatic code formatter ``black``. You can run it using + the nox session ``blacken``. This will eliminate many lint errors. Run via:: + + $ nox -s blacken + +- PEP8 compliance is required, with exceptions defined in the linter configuration. + If you have ``nox`` installed, you can test that you have not introduced + any non-compliant code via:: + + $ nox -s lint + +- In order to make ``nox -s lint`` run faster, you can set some environment + variables:: + + export GOOGLE_CLOUD_TESTING_REMOTE="upstream" + export GOOGLE_CLOUD_TESTING_BRANCH="main" + + By doing this, you are specifying the location of the most up-to-date + version of ``google-cloud-python``. The + remote name ``upstream`` should point to the official ``googleapis`` + checkout and the branch should be the default branch on that remote (``main``). + +- This repository contains configuration for the + `pre-commit `__ tool, which automates checking + our linters during a commit. If you have it installed on your ``$PATH``, + you can enable enforcing those checks via: + +.. code-block:: bash + + $ pre-commit install + pre-commit installed at .git/hooks/pre-commit + +Exceptions to PEP8: + +- Many unit tests use a helper method, ``_call_fut`` ("FUT" is short for + "Function-Under-Test"), which is PEP8-incompliant, but more readable. + Some also use a local variable, ``MUT`` (short for "Module-Under-Test"). + +******************** +Running System Tests +******************** + +- To run system tests, you can execute:: + + # Run all system tests + $ nox -s system + + # Run a single system test + $ nox -s system-3.12 -- -k + + + .. note:: + + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + For expediency, we do not run them in older versions of Python 3. + + This alone will not run the tests. You'll need to change some local + auth settings and change some configuration in your project to + run all the tests. + +- System tests will be run against an actual project. You should use local credentials from gcloud when possible. See `Best practices for application authentication `__. Some tests require a service account. For those tests see `Authenticating as a service account `__. + +************* +Test Coverage +************* + +- The codebase *must* have 100% test statement coverage after each commit. + You can test coverage via ``nox -s cover``. + +****************************************************** +Documentation Coverage and Building HTML Documentation +****************************************************** + +If you fix a bug, and the bug requires an API or behavior modification, all +documentation in this package which references that API or behavior must be +changed to reflect the bug fix, ideally in the same commit that fixes the bug +or adds the feature. + +Build the docs via: + + $ nox -s docs + +************************* +Samples and code snippets +************************* + +Code samples and snippets live in the `samples/` catalogue. Feel free to +provide more examples, but make sure to write tests for those examples. +Each folder containing example code requires its own `noxfile.py` script +which automates testing. If you decide to create a new folder, you can +base it on the `samples/snippets` folder (providing `noxfile.py` and +the requirements files). + +The tests will run against a real Google Cloud Project, so you should +configure them just like the System Tests. + +- To run sample tests, you can execute:: + + # Run all tests in a folder + $ cd samples/snippets + $ nox -s py-3.8 + + # Run a single sample test + $ cd samples/snippets + $ nox -s py-3.8 -- -k + +******************************************** +Note About ``README`` as it pertains to PyPI +******************************************** + +The `description on PyPI`_ for the project comes directly from the +``README``. Due to the reStructuredText (``rst``) parser used by +PyPI, relative links which will work on GitHub (e.g. ``CONTRIBUTING.rst`` +instead of +``https://github.com/googleapis/google-cloud-python/blob/main/CONTRIBUTING.rst``) +may cause problems creating links or rendering the description. + +.. _description on PyPI: https://pypi.org/project/google-cloud-parallelstore + + +************************* +Supported Python Versions +************************* + +We support: + +- `Python 3.7`_ +- `Python 3.8`_ +- `Python 3.9`_ +- `Python 3.10`_ +- `Python 3.11`_ +- `Python 3.12`_ + +.. _Python 3.7: https://docs.python.org/3.7/ +.. _Python 3.8: https://docs.python.org/3.8/ +.. _Python 3.9: https://docs.python.org/3.9/ +.. _Python 3.10: https://docs.python.org/3.10/ +.. _Python 3.11: https://docs.python.org/3.11/ +.. _Python 3.12: https://docs.python.org/3.12/ + + +Supported versions can be found in our ``noxfile.py`` `config`_. + +.. _config: https://github.com/googleapis/google-cloud-python/blob/main/packages/google-cloud-parallelstore/noxfile.py + + +********** +Versioning +********** + +This library follows `Semantic Versioning`_. + +.. _Semantic Versioning: http://semver.org/ + +Some packages are currently in major version zero (``0.y.z``), which means that +anything may change at any time and the public API should not be considered +stable. + +****************************** +Contributor License Agreements +****************************** + +Before we can accept your pull requests you'll need to sign a Contributor +License Agreement (CLA): + +- **If you are an individual writing original source code** and **you own the + intellectual property**, then you'll need to sign an + `individual CLA `__. +- **If you work for a company that wants to allow you to contribute your work**, + then you'll need to sign a + `corporate CLA `__. + +You can sign these electronically (just scroll to the bottom). After that, +we'll be able to accept your pull requests. diff --git a/packages/google-cloud-parallelstore/LICENSE b/packages/google-cloud-parallelstore/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/packages/google-cloud-parallelstore/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/packages/google-cloud-parallelstore/MANIFEST.in b/packages/google-cloud-parallelstore/MANIFEST.in new file mode 100644 index 000000000000..e0a66705318e --- /dev/null +++ b/packages/google-cloud-parallelstore/MANIFEST.in @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2023 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 +# +# https://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 by synthtool. DO NOT EDIT! +include README.rst LICENSE +recursive-include google *.json *.proto py.typed +recursive-include tests * +global-exclude *.py[co] +global-exclude __pycache__ + +# Exclude scripts for samples readmegen +prune scripts/readme-gen diff --git a/packages/google-cloud-parallelstore/README.rst b/packages/google-cloud-parallelstore/README.rst new file mode 100644 index 000000000000..f23c1253c0bb --- /dev/null +++ b/packages/google-cloud-parallelstore/README.rst @@ -0,0 +1,108 @@ +Python Client for Parallelstore API +=================================== + +|preview| |pypi| |versions| + +`Parallelstore API`_: Parallelstore is based on Intel DAOS and delivers up to 6.3x greater read throughput performance compared to competitive Lustre scratch offerings. + +- `Client Library Documentation`_ +- `Product Documentation`_ + +.. |preview| image:: https://img.shields.io/badge/support-preview-orange.svg + :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#stability-levels +.. |pypi| image:: https://img.shields.io/pypi/v/google-cloud-parallelstore.svg + :target: https://pypi.org/project/google-cloud-parallelstore/ +.. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-parallelstore.svg + :target: https://pypi.org/project/google-cloud-parallelstore/ +.. _Parallelstore API: https://cloud.google.com/parallelstore +.. _Client Library Documentation: https://cloud.google.com/python/docs/reference/google-cloud-parallelstore/latest +.. _Product Documentation: https://cloud.google.com/parallelstore + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. `Enable the Parallelstore API.`_ +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Enable the Parallelstore API.: https://cloud.google.com/parallelstore +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a virtual environment using `venv`_. `venv`_ is a tool that +creates isolated Python environments. These isolated environments can have separate +versions of Python packages, which allows you to isolate one project's dependencies +from the dependencies of other projects. + +With `venv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`venv`: https://docs.python.org/3/library/venv.html + + +Code samples and snippets +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Code samples and snippets live in the `samples/`_ folder. + +.. _samples/: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-parallelstore/samples + + +Supported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^ +Our client libraries are compatible with all current `active`_ and `maintenance`_ versions of +Python. + +Python >= 3.7 + +.. _active: https://devguide.python.org/devcycle/#in-development-main-branch +.. _maintenance: https://devguide.python.org/devcycle/#maintenance-branches + +Unsupported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Python <= 3.6 + +If you are using an `end-of-life`_ +version of Python, we recommend that you update as soon as possible to an actively supported version. + +.. _end-of-life: https://devguide.python.org/devcycle/#end-of-life-branches + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + pip install google-cloud-parallelstore + + +Windows +^^^^^^^ + +.. code-block:: console + + py -m venv + .\\Scripts\activate + pip install google-cloud-parallelstore + +Next Steps +~~~~~~~~~~ + +- Read the `Client Library Documentation`_ for Parallelstore API + to see other available methods on the client. +- Read the `Parallelstore API Product documentation`_ to learn + more about the product and see How-to Guides. +- View this `README`_ to see the full list of Cloud + APIs that we cover. + +.. _Parallelstore API Product documentation: https://cloud.google.com/parallelstore +.. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst diff --git a/packages/google-cloud-parallelstore/docs/CHANGELOG.md b/packages/google-cloud-parallelstore/docs/CHANGELOG.md new file mode 120000 index 000000000000..04c99a55caae --- /dev/null +++ b/packages/google-cloud-parallelstore/docs/CHANGELOG.md @@ -0,0 +1 @@ +../CHANGELOG.md \ No newline at end of file diff --git a/packages/google-cloud-parallelstore/docs/README.rst b/packages/google-cloud-parallelstore/docs/README.rst new file mode 120000 index 000000000000..89a0106941ff --- /dev/null +++ b/packages/google-cloud-parallelstore/docs/README.rst @@ -0,0 +1 @@ +../README.rst \ No newline at end of file diff --git a/packages/google-cloud-parallelstore/docs/_static/custom.css b/packages/google-cloud-parallelstore/docs/_static/custom.css new file mode 100644 index 000000000000..b0a295464b23 --- /dev/null +++ b/packages/google-cloud-parallelstore/docs/_static/custom.css @@ -0,0 +1,20 @@ +div#python2-eol { + border-color: red; + border-width: medium; +} + +/* Ensure minimum width for 'Parameters' / 'Returns' column */ +dl.field-list > dt { + min-width: 100px +} + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/packages/google-cloud-parallelstore/docs/_templates/layout.html b/packages/google-cloud-parallelstore/docs/_templates/layout.html new file mode 100644 index 000000000000..6316a537f72b --- /dev/null +++ b/packages/google-cloud-parallelstore/docs/_templates/layout.html @@ -0,0 +1,50 @@ + +{% extends "!layout.html" %} +{%- block content %} +{%- if theme_fixed_sidebar|lower == 'true' %} +
+ {{ sidebar() }} + {%- block document %} +
+ {%- if render_sidebar %} +
+ {%- endif %} + + {%- block relbar_top %} + {%- if theme_show_relbar_top|tobool %} + + {%- endif %} + {% endblock %} + +
+
+ As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please + visit Python 2 support on Google Cloud. +
+ {% block body %} {% endblock %} +
+ + {%- block relbar_bottom %} + {%- if theme_show_relbar_bottom|tobool %} + + {%- endif %} + {% endblock %} + + {%- if render_sidebar %} +
+ {%- endif %} +
+ {%- endblock %} +
+
+{%- else %} +{{ super() }} +{%- endif %} +{%- endblock %} diff --git a/packages/google-cloud-parallelstore/docs/conf.py b/packages/google-cloud-parallelstore/docs/conf.py new file mode 100644 index 000000000000..92d443638c21 --- /dev/null +++ b/packages/google-cloud-parallelstore/docs/conf.py @@ -0,0 +1,384 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# +# google-cloud-parallelstore documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import os +import shlex +import sys + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + +__version__ = "" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.5.5" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.doctest", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", + "recommonmark", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_options = {"members": True} +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = "google-cloud-parallelstore" +copyright = "2019, Google" +author = "Google APIs" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [ + "_build", + "**/.nox/**/*", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for google-cloud-parallelstore", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-parallelstore-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + #'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + #'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + #'preamble': '', + # Latex figure (float) alignment + #'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-parallelstore.tex", + "google-cloud-parallelstore Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-parallelstore", + "google-cloud-parallelstore Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-parallelstore", + "google-cloud-parallelstore Documentation", + author, + "google-cloud-parallelstore", + "google-cloud-parallelstore Library", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), + "google.api_core": ( + "https://googleapis.dev/python/google-api-core/latest/", + None, + ), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/packages/google-cloud-parallelstore/docs/index.rst b/packages/google-cloud-parallelstore/docs/index.rst new file mode 100644 index 000000000000..4657e75774a9 --- /dev/null +++ b/packages/google-cloud-parallelstore/docs/index.rst @@ -0,0 +1,23 @@ +.. include:: README.rst + +.. include:: multiprocessing.rst + + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + parallelstore_v1beta/services_ + parallelstore_v1beta/types_ + + +Changelog +--------- + +For a list of all ``google-cloud-parallelstore`` releases: + +.. toctree:: + :maxdepth: 2 + + CHANGELOG diff --git a/packages/google-cloud-parallelstore/docs/multiprocessing.rst b/packages/google-cloud-parallelstore/docs/multiprocessing.rst new file mode 100644 index 000000000000..536d17b2ea65 --- /dev/null +++ b/packages/google-cloud-parallelstore/docs/multiprocessing.rst @@ -0,0 +1,7 @@ +.. note:: + + Because this client uses :mod:`grpc` library, it is safe to + share instances across threads. In multiprocessing scenarios, the best + practice is to create client instances *after* the invocation of + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or + :class:`multiprocessing.Process`. diff --git a/packages/google-cloud-parallelstore/docs/parallelstore_v1beta/parallelstore.rst b/packages/google-cloud-parallelstore/docs/parallelstore_v1beta/parallelstore.rst new file mode 100644 index 000000000000..82e8b6507690 --- /dev/null +++ b/packages/google-cloud-parallelstore/docs/parallelstore_v1beta/parallelstore.rst @@ -0,0 +1,10 @@ +Parallelstore +------------------------------- + +.. automodule:: google.cloud.parallelstore_v1beta.services.parallelstore + :members: + :inherited-members: + +.. automodule:: google.cloud.parallelstore_v1beta.services.parallelstore.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-parallelstore/docs/parallelstore_v1beta/services_.rst b/packages/google-cloud-parallelstore/docs/parallelstore_v1beta/services_.rst new file mode 100644 index 000000000000..22671c2edf73 --- /dev/null +++ b/packages/google-cloud-parallelstore/docs/parallelstore_v1beta/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Parallelstore v1beta API +================================================== +.. toctree:: + :maxdepth: 2 + + parallelstore diff --git a/packages/google-cloud-parallelstore/docs/parallelstore_v1beta/types_.rst b/packages/google-cloud-parallelstore/docs/parallelstore_v1beta/types_.rst new file mode 100644 index 000000000000..4fd25f03a091 --- /dev/null +++ b/packages/google-cloud-parallelstore/docs/parallelstore_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Parallelstore v1beta API +=============================================== + +.. automodule:: google.cloud.parallelstore_v1beta.types + :members: + :show-inheritance: diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore/__init__.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore/__init__.py new file mode 100644 index 000000000000..66e8f4147492 --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore/__init__.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 google.cloud.parallelstore import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.parallelstore_v1beta.services.parallelstore.async_client import ( + ParallelstoreAsyncClient, +) +from google.cloud.parallelstore_v1beta.services.parallelstore.client import ( + ParallelstoreClient, +) +from google.cloud.parallelstore_v1beta.types.parallelstore import ( + CreateInstanceRequest, + DeleteInstanceRequest, + GetInstanceRequest, + Instance, + ListInstancesRequest, + ListInstancesResponse, + OperationMetadata, + UpdateInstanceRequest, +) + +__all__ = ( + "ParallelstoreClient", + "ParallelstoreAsyncClient", + "CreateInstanceRequest", + "DeleteInstanceRequest", + "GetInstanceRequest", + "Instance", + "ListInstancesRequest", + "ListInstancesResponse", + "OperationMetadata", + "UpdateInstanceRequest", +) diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore/gapic_version.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore/gapic_version.py new file mode 100644 index 000000000000..123d60293175 --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# +__version__ = "0.1.1" # {x-release-please-version} diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore/py.typed b/packages/google-cloud-parallelstore/google/cloud/parallelstore/py.typed new file mode 100644 index 000000000000..743160d56b7b --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-parallelstore package uses inline types. diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/__init__.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/__init__.py new file mode 100644 index 000000000000..3e6f336fcdbf --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/__init__.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 google.cloud.parallelstore_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.parallelstore import ParallelstoreAsyncClient, ParallelstoreClient +from .types.parallelstore import ( + CreateInstanceRequest, + DeleteInstanceRequest, + GetInstanceRequest, + Instance, + ListInstancesRequest, + ListInstancesResponse, + OperationMetadata, + UpdateInstanceRequest, +) + +__all__ = ( + "ParallelstoreAsyncClient", + "CreateInstanceRequest", + "DeleteInstanceRequest", + "GetInstanceRequest", + "Instance", + "ListInstancesRequest", + "ListInstancesResponse", + "OperationMetadata", + "ParallelstoreClient", + "UpdateInstanceRequest", +) diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/gapic_metadata.json b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..4548b04b30a7 --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/gapic_metadata.json @@ -0,0 +1,103 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.parallelstore_v1beta", + "protoPackage": "google.cloud.parallelstore.v1beta", + "schema": "1.0", + "services": { + "Parallelstore": { + "clients": { + "grpc": { + "libraryClient": "ParallelstoreClient", + "rpcs": { + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "UpdateInstance": { + "methods": [ + "update_instance" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ParallelstoreAsyncClient", + "rpcs": { + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "UpdateInstance": { + "methods": [ + "update_instance" + ] + } + } + }, + "rest": { + "libraryClient": "ParallelstoreClient", + "rpcs": { + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "UpdateInstance": { + "methods": [ + "update_instance" + ] + } + } + } + } + } + } +} diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/gapic_version.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/gapic_version.py new file mode 100644 index 000000000000..123d60293175 --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# +__version__ = "0.1.1" # {x-release-please-version} diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/py.typed b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/py.typed new file mode 100644 index 000000000000..743160d56b7b --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-parallelstore package uses inline types. diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/__init__.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/__init__.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/__init__.py new file mode 100644 index 000000000000..47e73b987a21 --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .async_client import ParallelstoreAsyncClient +from .client import ParallelstoreClient + +__all__ = ( + "ParallelstoreClient", + "ParallelstoreAsyncClient", +) diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/async_client.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/async_client.py new file mode 100644 index 000000000000..4b9829150fe5 --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/async_client.py @@ -0,0 +1,1281 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.parallelstore_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.parallelstore_v1beta.services.parallelstore import pagers +from google.cloud.parallelstore_v1beta.types import parallelstore + +from .client import ParallelstoreClient +from .transports.base import DEFAULT_CLIENT_INFO, ParallelstoreTransport +from .transports.grpc_asyncio import ParallelstoreGrpcAsyncIOTransport + + +class ParallelstoreAsyncClient: + """Service describing handlers for resources Configures and manages + parallelstore resources. + + Parallelstore service. + + The ``parallelstore.googleapis.com`` service implements the + parallelstore API and defines the following resource model for + managing instances: + + - The service works with a collection of cloud projects, named: + ``/projects/*`` + - Each project has a collection of available locations, named: + ``/locations/*`` + - Each location has a collection of instances named + ``/instances/*``. + - Parallelstore instances are resources of the form: + ``/projects/{project_id}/locations/{location_id}/instances/{instance_id}`` + + Note that location_id must be a Google Cloud ``zone``; for example: + + - ``projects/12345/locations/us-central1-c/instances/my-parallelstore-share`` + """ + + _client: ParallelstoreClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ParallelstoreClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ParallelstoreClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ParallelstoreClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ParallelstoreClient._DEFAULT_UNIVERSE + + address_path = staticmethod(ParallelstoreClient.address_path) + parse_address_path = staticmethod(ParallelstoreClient.parse_address_path) + instance_path = staticmethod(ParallelstoreClient.instance_path) + parse_instance_path = staticmethod(ParallelstoreClient.parse_instance_path) + network_path = staticmethod(ParallelstoreClient.network_path) + parse_network_path = staticmethod(ParallelstoreClient.parse_network_path) + common_billing_account_path = staticmethod( + ParallelstoreClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + ParallelstoreClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(ParallelstoreClient.common_folder_path) + parse_common_folder_path = staticmethod( + ParallelstoreClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + ParallelstoreClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + ParallelstoreClient.parse_common_organization_path + ) + common_project_path = staticmethod(ParallelstoreClient.common_project_path) + parse_common_project_path = staticmethod( + ParallelstoreClient.parse_common_project_path + ) + common_location_path = staticmethod(ParallelstoreClient.common_location_path) + parse_common_location_path = staticmethod( + ParallelstoreClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ParallelstoreAsyncClient: The constructed client. + """ + return ParallelstoreClient.from_service_account_info.__func__(ParallelstoreAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ParallelstoreAsyncClient: The constructed client. + """ + return ParallelstoreClient.from_service_account_file.__func__(ParallelstoreAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return ParallelstoreClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ParallelstoreTransport: + """Returns the transport used by the client instance. + + Returns: + ParallelstoreTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial( + type(ParallelstoreClient).get_transport_class, type(ParallelstoreClient) + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ParallelstoreTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the parallelstore async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ParallelstoreTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ParallelstoreClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_instances( + self, + request: Optional[Union[parallelstore.ListInstancesRequest, 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.ListInstancesAsyncPager: + r"""Lists Instances in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import parallelstore_v1beta + + async def sample_list_instances(): + # Create a client + client = parallelstore_v1beta.ParallelstoreAsyncClient() + + # Initialize request argument(s) + request = parallelstore_v1beta.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.parallelstore_v1beta.types.ListInstancesRequest, dict]]): + The request object. Message for requesting list of + Instances + parent (:class:`str`): + Required. The project and location for which to retrieve + instance information, in the format + ``projects/{project_id}/locations/{location}``. For + Parallelstore locations map to Google Cloud zones, for + example **us-central1-a**. To retrieve instance + information for all locations, use "-" for the + ``{location}`` value. + + 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.parallelstore_v1beta.services.parallelstore.pagers.ListInstancesAsyncPager: + Message for response to listing + Instances + 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." + ) + + request = parallelstore.ListInstancesRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_instances, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListInstancesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_instance( + self, + request: Optional[Union[parallelstore.GetInstanceRequest, 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]] = (), + ) -> parallelstore.Instance: + r"""Gets details of a single Instance. + + .. 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 parallelstore_v1beta + + async def sample_get_instance(): + # Create a client + client = parallelstore_v1beta.ParallelstoreAsyncClient() + + # Initialize request argument(s) + request = parallelstore_v1beta.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.parallelstore_v1beta.types.GetInstanceRequest, dict]]): + The request object. Request to get an instance's details. + name (:class:`str`): + Required. The instance resource name, in the format + ``projects/{project_id}/locations/{location}/instances/{instance_id}``. + + 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.parallelstore_v1beta.types.Instance: + A Parallelstore instance. + """ + # 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." + ) + + request = parallelstore.GetInstanceRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_instance, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 create_instance( + self, + request: Optional[Union[parallelstore.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[parallelstore.Instance] = None, + instance_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"""Creates a Parallelstore instance in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import parallelstore_v1beta + + async def sample_create_instance(): + # Create a client + client = parallelstore_v1beta.ParallelstoreAsyncClient() + + # Initialize request argument(s) + instance = parallelstore_v1beta.Instance() + instance.capacity_gib = 1247 + + request = parallelstore_v1beta.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.parallelstore_v1beta.types.CreateInstanceRequest, dict]]): + The request object. Request for + [CreateInstance][google.cloud.parallelstore.v1beta.Parallelstore.CreateInstance] + parent (:class:`str`): + Required. The instance's project and location, in the + format ``projects/{project}/locations/{location}``. + Locations map to Google Cloud zones, for example + **us-west1-b**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (:class:`google.cloud.parallelstore_v1beta.types.Instance`): + Required. The instance to create. + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_id (:class:`str`): + Required. The logical name of the Parallelstore instance + in the user project with the following restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + - Must be unique within the customer project / location + + This corresponds to the ``instance_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.parallelstore_v1beta.types.Instance` + A Parallelstore instance. + + """ + # 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, instance, instance_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." + ) + + request = parallelstore.CreateInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + if instance_id is not None: + request.instance_id = instance_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_instance, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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, + parallelstore.Instance, + metadata_type=parallelstore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_instance( + self, + request: Optional[Union[parallelstore.UpdateInstanceRequest, dict]] = None, + *, + instance: Optional[parallelstore.Instance] = 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"""Updates the parameters of a single Instance. + + .. 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 parallelstore_v1beta + + async def sample_update_instance(): + # Create a client + client = parallelstore_v1beta.ParallelstoreAsyncClient() + + # Initialize request argument(s) + instance = parallelstore_v1beta.Instance() + instance.capacity_gib = 1247 + + request = parallelstore_v1beta.UpdateInstanceRequest( + instance=instance, + ) + + # Make the request + operation = client.update_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.parallelstore_v1beta.types.UpdateInstanceRequest, dict]]): + The request object. Message for updating a Instance + instance (:class:`google.cloud.parallelstore_v1beta.types.Instance`): + Required. The instance to update + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Mask of fields to update .Field mask is used + to specify the fields to be overwritten in the Instance + resource by the update. At least one path must be + supplied in this field. The fields specified in the + update_mask are relative to the resource, not the full + request. + + 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.parallelstore_v1beta.types.Instance` + A Parallelstore instance. + + """ + # 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([instance, 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." + ) + + request = parallelstore.UpdateInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance is not None: + request.instance = instance + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_instance, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("instance.name", request.instance.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, + parallelstore.Instance, + metadata_type=parallelstore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_instance( + self, + request: Optional[Union[parallelstore.DeleteInstanceRequest, 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 single Instance. + + .. 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 parallelstore_v1beta + + async def sample_delete_instance(): + # Create a client + client = parallelstore_v1beta.ParallelstoreAsyncClient() + + # Initialize request argument(s) + request = parallelstore_v1beta.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.parallelstore_v1beta.types.DeleteInstanceRequest, dict]]): + The request object. Message for deleting a Instance + name (:class:`str`): + Required. Name of the resource + 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." + ) + + request = parallelstore.DeleteInstanceRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_instance, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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=parallelstore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` 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: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` 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: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` 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: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` 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: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 __aenter__(self) -> "ParallelstoreAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("ParallelstoreAsyncClient",) diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/client.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/client.py new file mode 100644 index 000000000000..d80af52675f4 --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/client.py @@ -0,0 +1,1736 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.parallelstore_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.parallelstore_v1beta.services.parallelstore import pagers +from google.cloud.parallelstore_v1beta.types import parallelstore + +from .transports.base import DEFAULT_CLIENT_INFO, ParallelstoreTransport +from .transports.grpc import ParallelstoreGrpcTransport +from .transports.grpc_asyncio import ParallelstoreGrpcAsyncIOTransport +from .transports.rest import ParallelstoreRestTransport + + +class ParallelstoreClientMeta(type): + """Metaclass for the Parallelstore client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[ParallelstoreTransport]] + _transport_registry["grpc"] = ParallelstoreGrpcTransport + _transport_registry["grpc_asyncio"] = ParallelstoreGrpcAsyncIOTransport + _transport_registry["rest"] = ParallelstoreRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ParallelstoreTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ParallelstoreClient(metaclass=ParallelstoreClientMeta): + """Service describing handlers for resources Configures and manages + parallelstore resources. + + Parallelstore service. + + The ``parallelstore.googleapis.com`` service implements the + parallelstore API and defines the following resource model for + managing instances: + + - The service works with a collection of cloud projects, named: + ``/projects/*`` + - Each project has a collection of available locations, named: + ``/locations/*`` + - Each location has a collection of instances named + ``/instances/*``. + - Parallelstore instances are resources of the form: + ``/projects/{project_id}/locations/{location_id}/instances/{instance_id}`` + + Note that location_id must be a Google Cloud ``zone``; for example: + + - ``projects/12345/locations/us-central1-c/instances/my-parallelstore-share`` + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "parallelstore.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "parallelstore.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ParallelstoreClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ParallelstoreClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ParallelstoreTransport: + """Returns the transport used by the client instance. + + Returns: + ParallelstoreTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def address_path( + project: str, + region: str, + address: str, + ) -> str: + """Returns a fully-qualified address string.""" + return "projects/{project}/regions/{region}/addresses/{address}".format( + project=project, + region=region, + address=address, + ) + + @staticmethod + def parse_address_path(path: str) -> Dict[str, str]: + """Parses a address path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/regions/(?P.+?)/addresses/(?P
.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def instance_path( + project: str, + location: str, + instance: str, + ) -> str: + """Returns a fully-qualified instance string.""" + return "projects/{project}/locations/{location}/instances/{instance}".format( + project=project, + location=location, + instance=instance, + ) + + @staticmethod + def parse_instance_path(path: str) -> Dict[str, str]: + """Parses a instance path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def network_path( + project: str, + network: str, + ) -> str: + """Returns a fully-qualified network string.""" + return "projects/{project}/global/networks/{network}".format( + project=project, + network=network, + ) + + @staticmethod + def parse_network_path(path: str) -> Dict[str, str]: + """Parses a network path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/global/networks/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = ParallelstoreClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = ParallelstoreClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ParallelstoreClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = ParallelstoreClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = ParallelstoreClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError( + "The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default." + ) + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = ( + self._is_universe_domain_valid + or ParallelstoreClient._compare_universes( + self.universe_domain, self.transport._credentials + ) + ) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ParallelstoreTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the parallelstore client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ParallelstoreTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = ParallelstoreClient._read_environment_variables() + self._client_cert_source = ParallelstoreClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = ParallelstoreClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, ParallelstoreTransport) + if transport_provided: + # transport is a ParallelstoreTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(ParallelstoreTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or ParallelstoreClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + Transport = type(self).get_transport_class(cast(str, transport)) + self._transport = Transport( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def list_instances( + self, + request: Optional[Union[parallelstore.ListInstancesRequest, 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.ListInstancesPager: + r"""Lists Instances in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import parallelstore_v1beta + + def sample_list_instances(): + # Create a client + client = parallelstore_v1beta.ParallelstoreClient() + + # Initialize request argument(s) + request = parallelstore_v1beta.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.parallelstore_v1beta.types.ListInstancesRequest, dict]): + The request object. Message for requesting list of + Instances + parent (str): + Required. The project and location for which to retrieve + instance information, in the format + ``projects/{project_id}/locations/{location}``. For + Parallelstore locations map to Google Cloud zones, for + example **us-central1-a**. To retrieve instance + information for all locations, use "-" for the + ``{location}`` value. + + 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.parallelstore_v1beta.services.parallelstore.pagers.ListInstancesPager: + Message for response to listing + Instances + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a parallelstore.ListInstancesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, parallelstore.ListInstancesRequest): + request = parallelstore.ListInstancesRequest(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_instances] + + # 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.ListInstancesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_instance( + self, + request: Optional[Union[parallelstore.GetInstanceRequest, 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]] = (), + ) -> parallelstore.Instance: + r"""Gets details of a single Instance. + + .. 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 parallelstore_v1beta + + def sample_get_instance(): + # Create a client + client = parallelstore_v1beta.ParallelstoreClient() + + # Initialize request argument(s) + request = parallelstore_v1beta.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.parallelstore_v1beta.types.GetInstanceRequest, dict]): + The request object. Request to get an instance's details. + name (str): + Required. The instance resource name, in the format + ``projects/{project_id}/locations/{location}/instances/{instance_id}``. + + 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.parallelstore_v1beta.types.Instance: + A Parallelstore instance. + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a parallelstore.GetInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, parallelstore.GetInstanceRequest): + request = parallelstore.GetInstanceRequest(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_instance] + + # 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 create_instance( + self, + request: Optional[Union[parallelstore.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[parallelstore.Instance] = None, + instance_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"""Creates a Parallelstore instance in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import parallelstore_v1beta + + def sample_create_instance(): + # Create a client + client = parallelstore_v1beta.ParallelstoreClient() + + # Initialize request argument(s) + instance = parallelstore_v1beta.Instance() + instance.capacity_gib = 1247 + + request = parallelstore_v1beta.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.parallelstore_v1beta.types.CreateInstanceRequest, dict]): + The request object. Request for + [CreateInstance][google.cloud.parallelstore.v1beta.Parallelstore.CreateInstance] + parent (str): + Required. The instance's project and location, in the + format ``projects/{project}/locations/{location}``. + Locations map to Google Cloud zones, for example + **us-west1-b**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (google.cloud.parallelstore_v1beta.types.Instance): + Required. The instance to create. + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_id (str): + Required. The logical name of the Parallelstore instance + in the user project with the following restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + - Must be unique within the customer project / location + + This corresponds to the ``instance_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.parallelstore_v1beta.types.Instance` + A Parallelstore instance. + + """ + # 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, instance, instance_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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a parallelstore.CreateInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, parallelstore.CreateInstanceRequest): + request = parallelstore.CreateInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + if instance_id is not None: + request.instance_id = instance_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_instance] + + # 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, + parallelstore.Instance, + metadata_type=parallelstore.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_instance( + self, + request: Optional[Union[parallelstore.UpdateInstanceRequest, dict]] = None, + *, + instance: Optional[parallelstore.Instance] = 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"""Updates the parameters of a single Instance. + + .. 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 parallelstore_v1beta + + def sample_update_instance(): + # Create a client + client = parallelstore_v1beta.ParallelstoreClient() + + # Initialize request argument(s) + instance = parallelstore_v1beta.Instance() + instance.capacity_gib = 1247 + + request = parallelstore_v1beta.UpdateInstanceRequest( + instance=instance, + ) + + # Make the request + operation = client.update_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.parallelstore_v1beta.types.UpdateInstanceRequest, dict]): + The request object. Message for updating a Instance + instance (google.cloud.parallelstore_v1beta.types.Instance): + Required. The instance to update + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask of fields to update .Field mask is used + to specify the fields to be overwritten in the Instance + resource by the update. At least one path must be + supplied in this field. The fields specified in the + update_mask are relative to the resource, not the full + request. + + 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.parallelstore_v1beta.types.Instance` + A Parallelstore instance. + + """ + # 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([instance, 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a parallelstore.UpdateInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, parallelstore.UpdateInstanceRequest): + request = parallelstore.UpdateInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance is not None: + request.instance = instance + 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_instance] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("instance.name", request.instance.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, + parallelstore.Instance, + metadata_type=parallelstore.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_instance( + self, + request: Optional[Union[parallelstore.DeleteInstanceRequest, 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 single Instance. + + .. 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 parallelstore_v1beta + + def sample_delete_instance(): + # Create a client + client = parallelstore_v1beta.ParallelstoreClient() + + # Initialize request argument(s) + request = parallelstore_v1beta.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.parallelstore_v1beta.types.DeleteInstanceRequest, dict]): + The request object. Message for deleting a Instance + name (str): + Required. Name of the resource + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a parallelstore.DeleteInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, parallelstore.DeleteInstanceRequest): + request = parallelstore.DeleteInstanceRequest(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_instance] + + # 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=parallelstore.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ParallelstoreClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` 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.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` 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: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` 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: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` 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: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("ParallelstoreClient",) diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/pagers.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/pagers.py new file mode 100644 index 000000000000..9d1abee1429f --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/pagers.py @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.parallelstore_v1beta.types import parallelstore + + +class ListInstancesPager: + """A pager for iterating through ``list_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.parallelstore_v1beta.types.ListInstancesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``instances`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListInstances`` requests and continue to iterate + through the ``instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.parallelstore_v1beta.types.ListInstancesResponse` + 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[..., parallelstore.ListInstancesResponse], + request: parallelstore.ListInstancesRequest, + response: parallelstore.ListInstancesResponse, + *, + 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.parallelstore_v1beta.types.ListInstancesRequest): + The initial request object. + response (google.cloud.parallelstore_v1beta.types.ListInstancesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = parallelstore.ListInstancesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[parallelstore.ListInstancesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[parallelstore.Instance]: + for page in self.pages: + yield from page.instances + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListInstancesAsyncPager: + """A pager for iterating through ``list_instances`` requests. + + This class thinly wraps an initial + :class:`google.cloud.parallelstore_v1beta.types.ListInstancesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``instances`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListInstances`` requests and continue to iterate + through the ``instances`` field on the + corresponding responses. + + All the usual :class:`google.cloud.parallelstore_v1beta.types.ListInstancesResponse` + 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[parallelstore.ListInstancesResponse]], + request: parallelstore.ListInstancesRequest, + response: parallelstore.ListInstancesResponse, + *, + 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.parallelstore_v1beta.types.ListInstancesRequest): + The initial request object. + response (google.cloud.parallelstore_v1beta.types.ListInstancesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = parallelstore.ListInstancesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[parallelstore.ListInstancesResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[parallelstore.Instance]: + async def async_generator(): + async for page in self.pages: + for response in page.instances: + 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-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/__init__.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/__init__.py new file mode 100644 index 000000000000..cebb16f25a47 --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ParallelstoreTransport +from .grpc import ParallelstoreGrpcTransport +from .grpc_asyncio import ParallelstoreGrpcAsyncIOTransport +from .rest import ParallelstoreRestInterceptor, ParallelstoreRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ParallelstoreTransport]] +_transport_registry["grpc"] = ParallelstoreGrpcTransport +_transport_registry["grpc_asyncio"] = ParallelstoreGrpcAsyncIOTransport +_transport_registry["rest"] = ParallelstoreRestTransport + +__all__ = ( + "ParallelstoreTransport", + "ParallelstoreGrpcTransport", + "ParallelstoreGrpcAsyncIOTransport", + "ParallelstoreRestTransport", + "ParallelstoreRestInterceptor", +) diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/base.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/base.py new file mode 100644 index 000000000000..5c877d2e8d6d --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/base.py @@ -0,0 +1,279 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.parallelstore_v1beta import gapic_version as package_version +from google.cloud.parallelstore_v1beta.types import parallelstore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class ParallelstoreTransport(abc.ABC): + """Abstract transport class for Parallelstore.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "parallelstore.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'parallelstore.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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_instances: gapic_v1.method.wrap_method( + self.list_instances, + default_timeout=None, + client_info=client_info, + ), + self.get_instance: gapic_v1.method.wrap_method( + self.get_instance, + default_timeout=None, + client_info=client_info, + ), + self.create_instance: gapic_v1.method.wrap_method( + self.create_instance, + default_timeout=None, + client_info=client_info, + ), + self.update_instance: gapic_v1.method.wrap_method( + self.update_instance, + default_timeout=None, + client_info=client_info, + ), + self.delete_instance: gapic_v1.method.wrap_method( + self.delete_instance, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_instances( + self, + ) -> Callable[ + [parallelstore.ListInstancesRequest], + Union[ + parallelstore.ListInstancesResponse, + Awaitable[parallelstore.ListInstancesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_instance( + self, + ) -> Callable[ + [parallelstore.GetInstanceRequest], + Union[parallelstore.Instance, Awaitable[parallelstore.Instance]], + ]: + raise NotImplementedError() + + @property + def create_instance( + self, + ) -> Callable[ + [parallelstore.CreateInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_instance( + self, + ) -> Callable[ + [parallelstore.UpdateInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_instance( + self, + ) -> Callable[ + [parallelstore.DeleteInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None,]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("ParallelstoreTransport",) diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/grpc.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/grpc.py new file mode 100644 index 000000000000..d0045c568cfe --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/grpc.py @@ -0,0 +1,515 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import grpc # type: ignore + +from google.cloud.parallelstore_v1beta.types import parallelstore + +from .base import DEFAULT_CLIENT_INFO, ParallelstoreTransport + + +class ParallelstoreGrpcTransport(ParallelstoreTransport): + """gRPC backend transport for Parallelstore. + + Service describing handlers for resources Configures and manages + parallelstore resources. + + Parallelstore service. + + The ``parallelstore.googleapis.com`` service implements the + parallelstore API and defines the following resource model for + managing instances: + + - The service works with a collection of cloud projects, named: + ``/projects/*`` + - Each project has a collection of available locations, named: + ``/locations/*`` + - Each location has a collection of instances named + ``/instances/*``. + - Parallelstore instances are resources of the form: + ``/projects/{project_id}/locations/{location_id}/instances/{instance_id}`` + + Note that location_id must be a Google Cloud ``zone``; for example: + + - ``projects/12345/locations/us-central1-c/instances/my-parallelstore-share`` + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "parallelstore.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'parallelstore.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. + This argument is ignored if ``channel`` is provided. + 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. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "parallelstore.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient(self.grpc_channel) + + # Return the client from cache. + return self._operations_client + + @property + def list_instances( + self, + ) -> Callable[ + [parallelstore.ListInstancesRequest], parallelstore.ListInstancesResponse + ]: + r"""Return a callable for the list instances method over gRPC. + + Lists Instances in a given project and location. + + Returns: + Callable[[~.ListInstancesRequest], + ~.ListInstancesResponse]: + 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_instances" not in self._stubs: + self._stubs["list_instances"] = self.grpc_channel.unary_unary( + "/google.cloud.parallelstore.v1beta.Parallelstore/ListInstances", + request_serializer=parallelstore.ListInstancesRequest.serialize, + response_deserializer=parallelstore.ListInstancesResponse.deserialize, + ) + return self._stubs["list_instances"] + + @property + def get_instance( + self, + ) -> Callable[[parallelstore.GetInstanceRequest], parallelstore.Instance]: + r"""Return a callable for the get instance method over gRPC. + + Gets details of a single Instance. + + Returns: + Callable[[~.GetInstanceRequest], + ~.Instance]: + 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_instance" not in self._stubs: + self._stubs["get_instance"] = self.grpc_channel.unary_unary( + "/google.cloud.parallelstore.v1beta.Parallelstore/GetInstance", + request_serializer=parallelstore.GetInstanceRequest.serialize, + response_deserializer=parallelstore.Instance.deserialize, + ) + return self._stubs["get_instance"] + + @property + def create_instance( + self, + ) -> Callable[[parallelstore.CreateInstanceRequest], operations_pb2.Operation]: + r"""Return a callable for the create instance method over gRPC. + + Creates a Parallelstore instance in a given project + and location. + + Returns: + Callable[[~.CreateInstanceRequest], + ~.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_instance" not in self._stubs: + self._stubs["create_instance"] = self.grpc_channel.unary_unary( + "/google.cloud.parallelstore.v1beta.Parallelstore/CreateInstance", + request_serializer=parallelstore.CreateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_instance"] + + @property + def update_instance( + self, + ) -> Callable[[parallelstore.UpdateInstanceRequest], operations_pb2.Operation]: + r"""Return a callable for the update instance method over gRPC. + + Updates the parameters of a single Instance. + + Returns: + Callable[[~.UpdateInstanceRequest], + ~.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_instance" not in self._stubs: + self._stubs["update_instance"] = self.grpc_channel.unary_unary( + "/google.cloud.parallelstore.v1beta.Parallelstore/UpdateInstance", + request_serializer=parallelstore.UpdateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_instance"] + + @property + def delete_instance( + self, + ) -> Callable[[parallelstore.DeleteInstanceRequest], operations_pb2.Operation]: + r"""Return a callable for the delete instance method over gRPC. + + Deletes a single Instance. + + Returns: + Callable[[~.DeleteInstanceRequest], + ~.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_instance" not in self._stubs: + self._stubs["delete_instance"] = self.grpc_channel.unary_unary( + "/google.cloud.parallelstore.v1beta.Parallelstore/DeleteInstance", + request_serializer=parallelstore.DeleteInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_instance"] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # 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_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # 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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # 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_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # 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_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # 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_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # 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_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("ParallelstoreGrpcTransport",) diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/grpc_asyncio.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/grpc_asyncio.py new file mode 100644 index 000000000000..e2719b762fc5 --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/grpc_asyncio.py @@ -0,0 +1,525 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.parallelstore_v1beta.types import parallelstore + +from .base import DEFAULT_CLIENT_INFO, ParallelstoreTransport +from .grpc import ParallelstoreGrpcTransport + + +class ParallelstoreGrpcAsyncIOTransport(ParallelstoreTransport): + """gRPC AsyncIO backend transport for Parallelstore. + + Service describing handlers for resources Configures and manages + parallelstore resources. + + Parallelstore service. + + The ``parallelstore.googleapis.com`` service implements the + parallelstore API and defines the following resource model for + managing instances: + + - The service works with a collection of cloud projects, named: + ``/projects/*`` + - Each project has a collection of available locations, named: + ``/locations/*`` + - Each location has a collection of instances named + ``/instances/*``. + - Parallelstore instances are resources of the form: + ``/projects/{project_id}/locations/{location_id}/instances/{instance_id}`` + + Note that location_id must be a Google Cloud ``zone``; for example: + + - ``projects/12345/locations/us-central1-c/instances/my-parallelstore-share`` + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "parallelstore.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "parallelstore.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'parallelstore.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. + This argument is ignored if ``channel`` is provided. + 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_instances( + self, + ) -> Callable[ + [parallelstore.ListInstancesRequest], + Awaitable[parallelstore.ListInstancesResponse], + ]: + r"""Return a callable for the list instances method over gRPC. + + Lists Instances in a given project and location. + + Returns: + Callable[[~.ListInstancesRequest], + Awaitable[~.ListInstancesResponse]]: + 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_instances" not in self._stubs: + self._stubs["list_instances"] = self.grpc_channel.unary_unary( + "/google.cloud.parallelstore.v1beta.Parallelstore/ListInstances", + request_serializer=parallelstore.ListInstancesRequest.serialize, + response_deserializer=parallelstore.ListInstancesResponse.deserialize, + ) + return self._stubs["list_instances"] + + @property + def get_instance( + self, + ) -> Callable[ + [parallelstore.GetInstanceRequest], Awaitable[parallelstore.Instance] + ]: + r"""Return a callable for the get instance method over gRPC. + + Gets details of a single Instance. + + Returns: + Callable[[~.GetInstanceRequest], + Awaitable[~.Instance]]: + 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_instance" not in self._stubs: + self._stubs["get_instance"] = self.grpc_channel.unary_unary( + "/google.cloud.parallelstore.v1beta.Parallelstore/GetInstance", + request_serializer=parallelstore.GetInstanceRequest.serialize, + response_deserializer=parallelstore.Instance.deserialize, + ) + return self._stubs["get_instance"] + + @property + def create_instance( + self, + ) -> Callable[ + [parallelstore.CreateInstanceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create instance method over gRPC. + + Creates a Parallelstore instance in a given project + and location. + + Returns: + Callable[[~.CreateInstanceRequest], + 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_instance" not in self._stubs: + self._stubs["create_instance"] = self.grpc_channel.unary_unary( + "/google.cloud.parallelstore.v1beta.Parallelstore/CreateInstance", + request_serializer=parallelstore.CreateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_instance"] + + @property + def update_instance( + self, + ) -> Callable[ + [parallelstore.UpdateInstanceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update instance method over gRPC. + + Updates the parameters of a single Instance. + + Returns: + Callable[[~.UpdateInstanceRequest], + 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_instance" not in self._stubs: + self._stubs["update_instance"] = self.grpc_channel.unary_unary( + "/google.cloud.parallelstore.v1beta.Parallelstore/UpdateInstance", + request_serializer=parallelstore.UpdateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_instance"] + + @property + def delete_instance( + self, + ) -> Callable[ + [parallelstore.DeleteInstanceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete instance method over gRPC. + + Deletes a single Instance. + + Returns: + Callable[[~.DeleteInstanceRequest], + 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_instance" not in self._stubs: + self._stubs["delete_instance"] = self.grpc_channel.unary_unary( + "/google.cloud.parallelstore.v1beta.Parallelstore/DeleteInstance", + request_serializer=parallelstore.DeleteInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_instance"] + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # 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_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # 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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # 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_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # 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_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # 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_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # 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_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ("ParallelstoreGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/rest.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/rest.py new file mode 100644 index 000000000000..1fdde7d6445d --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/services/parallelstore/transports/rest.py @@ -0,0 +1,1432 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import ( + gapic_v1, + operations_v1, + path_template, + rest_helpers, + rest_streaming, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.parallelstore_v1beta.types import parallelstore + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import ParallelstoreTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ParallelstoreRestInterceptor: + """Interceptor for Parallelstore. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the ParallelstoreRestTransport. + + .. code-block:: python + class MyCustomParallelstoreInterceptor(ParallelstoreRestInterceptor): + def pre_create_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_instances(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_instance(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ParallelstoreRestTransport(interceptor=MyCustomParallelstoreInterceptor()) + client = ParallelstoreClient(transport=transport) + + + """ + + def pre_create_instance( + self, + request: parallelstore.CreateInstanceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[parallelstore.CreateInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Parallelstore server. + """ + return request, metadata + + def post_create_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_instance + + Override in a subclass to manipulate the response + after it is returned by the Parallelstore server but before + it is returned to user code. + """ + return response + + def pre_delete_instance( + self, + request: parallelstore.DeleteInstanceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[parallelstore.DeleteInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Parallelstore server. + """ + return request, metadata + + def post_delete_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_instance + + Override in a subclass to manipulate the response + after it is returned by the Parallelstore server but before + it is returned to user code. + """ + return response + + def pre_get_instance( + self, + request: parallelstore.GetInstanceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[parallelstore.GetInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Parallelstore server. + """ + return request, metadata + + def post_get_instance( + self, response: parallelstore.Instance + ) -> parallelstore.Instance: + """Post-rpc interceptor for get_instance + + Override in a subclass to manipulate the response + after it is returned by the Parallelstore server but before + it is returned to user code. + """ + return response + + def pre_list_instances( + self, + request: parallelstore.ListInstancesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[parallelstore.ListInstancesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the Parallelstore server. + """ + return request, metadata + + def post_list_instances( + self, response: parallelstore.ListInstancesResponse + ) -> parallelstore.ListInstancesResponse: + """Post-rpc interceptor for list_instances + + Override in a subclass to manipulate the response + after it is returned by the Parallelstore server but before + it is returned to user code. + """ + return response + + def pre_update_instance( + self, + request: parallelstore.UpdateInstanceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[parallelstore.UpdateInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Parallelstore server. + """ + return request, metadata + + def post_update_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_instance + + Override in a subclass to manipulate the response + after it is returned by the Parallelstore 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 Parallelstore 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 Parallelstore 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 Parallelstore 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 Parallelstore 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 Parallelstore 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 Parallelstore 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 Parallelstore 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 Parallelstore 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 Parallelstore 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 Parallelstore 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 Parallelstore 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 Parallelstore server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ParallelstoreRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ParallelstoreRestInterceptor + + +class ParallelstoreRestTransport(ParallelstoreTransport): + """REST backend transport for Parallelstore. + + Service describing handlers for resources Configures and manages + parallelstore resources. + + Parallelstore service. + + The ``parallelstore.googleapis.com`` service implements the + parallelstore API and defines the following resource model for + managing instances: + + - The service works with a collection of cloud projects, named: + ``/projects/*`` + - Each project has a collection of available locations, named: + ``/locations/*`` + - Each location has a collection of instances named + ``/instances/*``. + - Parallelstore instances are resources of the form: + ``/projects/{project_id}/locations/{location_id}/instances/{instance_id}`` + + Note that location_id must be a Google Cloud ``zone``; for example: + + - ``projects/12345/locations/us-central1-c/instances/my-parallelstore-share`` + + 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 = "parallelstore.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[ParallelstoreRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'parallelstore.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 + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + 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 ParallelstoreRestInterceptor() + 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": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1beta/{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="v1beta", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateInstance(ParallelstoreRestStub): + def __hash__(self): + return hash("CreateInstance") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "instanceId": "", + } + + @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 + } + + def __call__( + self, + request: parallelstore.CreateInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the create instance method over HTTP. + + Args: + request (~.parallelstore.CreateInstanceRequest): + The request object. Request for + [CreateInstance][google.cloud.parallelstore.v1beta.Parallelstore.CreateInstance] + 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: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*}/instances", + "body": "instance", + }, + ] + request, metadata = self._interceptor.pre_create_instance(request, metadata) + pb_request = parallelstore.CreateInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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_instance(resp) + return resp + + class _DeleteInstance(ParallelstoreRestStub): + def __hash__(self): + return hash("DeleteInstance") + + __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 + } + + def __call__( + self, + request: parallelstore.DeleteInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete instance method over HTTP. + + Args: + request (~.parallelstore.DeleteInstanceRequest): + The request object. Message for deleting a Instance + 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: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/instances/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_instance(request, metadata) + pb_request = parallelstore.DeleteInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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_instance(resp) + return resp + + class _GetInstance(ParallelstoreRestStub): + def __hash__(self): + return hash("GetInstance") + + __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 + } + + def __call__( + self, + request: parallelstore.GetInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> parallelstore.Instance: + r"""Call the get instance method over HTTP. + + Args: + request (~.parallelstore.GetInstanceRequest): + The request object. Request to get an instance's details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.parallelstore.Instance: + A Parallelstore instance. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/instances/*}", + }, + ] + request, metadata = self._interceptor.pre_get_instance(request, metadata) + pb_request = parallelstore.GetInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = parallelstore.Instance() + pb_resp = parallelstore.Instance.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_instance(resp) + return resp + + class _ListInstances(ParallelstoreRestStub): + def __hash__(self): + return hash("ListInstances") + + __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 + } + + def __call__( + self, + request: parallelstore.ListInstancesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> parallelstore.ListInstancesResponse: + r"""Call the list instances method over HTTP. + + Args: + request (~.parallelstore.ListInstancesRequest): + The request object. Message for requesting list of + Instances + 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: + ~.parallelstore.ListInstancesResponse: + Message for response to listing + Instances + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/instances", + }, + ] + request, metadata = self._interceptor.pre_list_instances(request, metadata) + pb_request = parallelstore.ListInstancesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = parallelstore.ListInstancesResponse() + pb_resp = parallelstore.ListInstancesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_instances(resp) + return resp + + class _UpdateInstance(ParallelstoreRestStub): + def __hash__(self): + return hash("UpdateInstance") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @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 + } + + def __call__( + self, + request: parallelstore.UpdateInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update instance method over HTTP. + + Args: + request (~.parallelstore.UpdateInstanceRequest): + The request object. Message for updating a Instance + 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: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{instance.name=projects/*/locations/*/instances/*}", + "body": "instance", + }, + ] + request, metadata = self._interceptor.pre_update_instance(request, metadata) + pb_request = parallelstore.UpdateInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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_update_instance(resp) + return resp + + @property + def create_instance( + self, + ) -> Callable[[parallelstore.CreateInstanceRequest], 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._CreateInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_instance( + self, + ) -> Callable[[parallelstore.DeleteInstanceRequest], 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._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_instance( + self, + ) -> Callable[[parallelstore.GetInstanceRequest], parallelstore.Instance]: + # 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._GetInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_instances( + self, + ) -> Callable[ + [parallelstore.ListInstancesRequest], parallelstore.ListInstancesResponse + ]: + # 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._ListInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_instance( + self, + ) -> Callable[[parallelstore.UpdateInstanceRequest], 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._UpdateInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(ParallelstoreRestStub): + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation 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: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(ParallelstoreRestStub): + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations 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: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*}/locations", + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(ParallelstoreRestStub): + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + body = json.dumps(transcoded_request["body"]) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=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 self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(ParallelstoreRestStub): + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # 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 self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(ParallelstoreRestStub): + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation 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: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(ParallelstoreRestStub): + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations 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.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ParallelstoreRestTransport",) diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/types/__init__.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/types/__init__.py new file mode 100644 index 000000000000..be7f46a5e0e5 --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/types/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .parallelstore import ( + CreateInstanceRequest, + DeleteInstanceRequest, + GetInstanceRequest, + Instance, + ListInstancesRequest, + ListInstancesResponse, + OperationMetadata, + UpdateInstanceRequest, +) + +__all__ = ( + "CreateInstanceRequest", + "DeleteInstanceRequest", + "GetInstanceRequest", + "Instance", + "ListInstancesRequest", + "ListInstancesResponse", + "OperationMetadata", + "UpdateInstanceRequest", +) diff --git a/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/types/parallelstore.py b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/types/parallelstore.py new file mode 100644 index 000000000000..6f18e9511bae --- /dev/null +++ b/packages/google-cloud-parallelstore/google/cloud/parallelstore_v1beta/types/parallelstore.py @@ -0,0 +1,486 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.parallelstore.v1beta", + manifest={ + "Instance", + "ListInstancesRequest", + "ListInstancesResponse", + "GetInstanceRequest", + "CreateInstanceRequest", + "UpdateInstanceRequest", + "DeleteInstanceRequest", + "OperationMetadata", + }, +) + + +class Instance(proto.Message): + r"""A Parallelstore instance. + + Attributes: + name (str): + Identifier. The resource name of the instance, in the format + ``projects/{project}/locations/{location}/instances/{instance_id}`` + description (str): + Optional. The description of the instance. + 2048 characters or less. + state (google.cloud.parallelstore_v1beta.types.Instance.State): + Output only. The instance state. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the instance was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the instance was + updated. + labels (MutableMapping[str, str]): + Optional. Cloud Labels are a flexible and lightweight + mechanism for organizing cloud resources into groups that + reflect a customer's organizational needs and deployment + strategies. Cloud Labels can be used to filter collections + of resources. They can be used to control how resource + metrics are aggregated. And they can be used as arguments to + policy management rules (e.g. route, firewall, load + balancing, etc.). + + - Label keys must be between 1 and 63 characters long and + must conform to the following regular expression: + ``[a-z][a-z0-9_-]{0,62}``. + - Label values must be between 0 and 63 characters long and + must conform to the regular expression + ``[a-z0-9_-]{0,63}``. + - No more than 64 labels can be associated with a given + resource. + + See https://goo.gl/xmQnxf for more information on and + examples of labels. + + If you plan to use labels in your own code, please note that + additional characters may be allowed in the future. + Therefore, you are advised to use an internal label + representation, such as JSON, which doesn't rely upon + specific characters being disallowed. For example, + representing labels as the string: name + "*" + value would + prove problematic if we were to allow "*" in a future + release. + capacity_gib (int): + Required. Immutable. Storage capacity of + Parallelstore instance in Gibibytes (GiB). + daos_version (str): + Output only. The version of DAOS software + running in the instance + access_points (MutableSequence[str]): + Output only. List of access_points. Contains a list of IPv4 + addresses used for client side configuration. + network (str): + Optional. Immutable. The name of the Google Compute Engine + `VPC network `__ to + which the instance is connected. + reserved_ip_range (str): + Optional. Immutable. Contains the id of + allocated IP address range associated with the + private service access connection for example, + "test-default" associated with IP range + 10.0.0.0/29. If no range id is provided all + ranges will be considered. + """ + + class State(proto.Enum): + r"""Represents the different states of a Parallelstore instance. + + Values: + STATE_UNSPECIFIED (0): + Not set. + CREATING (1): + The instance is being created. + ACTIVE (2): + The instance is available for use. + DELETING (3): + The instance is being deleted. + FAILED (4): + The instance is not usable. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETING = 3 + FAILED = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + 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, + ) + capacity_gib: int = proto.Field( + proto.INT64, + number=8, + ) + daos_version: str = proto.Field( + proto.STRING, + number=9, + ) + access_points: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + network: str = proto.Field( + proto.STRING, + number=11, + ) + reserved_ip_range: str = proto.Field( + proto.STRING, + number=12, + ) + + +class ListInstancesRequest(proto.Message): + r"""Message for requesting list of Instances + + Attributes: + parent (str): + Required. The project and location for which to retrieve + instance information, in the format + ``projects/{project_id}/locations/{location}``. For + Parallelstore locations map to Google Cloud zones, for + example **us-central1-a**. To retrieve instance information + for all locations, use "-" for the ``{location}`` value. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results the server should return. + filter (str): + Optional. Filtering results + order_by (str): + Optional. Hint for how to order the results + """ + + 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, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListInstancesResponse(proto.Message): + r"""Message for response to listing Instances + + Attributes: + instances (MutableSequence[google.cloud.parallelstore_v1beta.types.Instance]): + The list of Parallelstore Instances + next_page_token (str): + A token identifying a page of results the + server should return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + instances: MutableSequence["Instance"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Instance", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetInstanceRequest(proto.Message): + r"""Request to get an instance's details. + + Attributes: + name (str): + Required. The instance resource name, in the format + ``projects/{project_id}/locations/{location}/instances/{instance_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateInstanceRequest(proto.Message): + r"""Request for + [CreateInstance][google.cloud.parallelstore.v1beta.Parallelstore.CreateInstance] + + Attributes: + parent (str): + Required. The instance's project and location, in the format + ``projects/{project}/locations/{location}``. Locations map + to Google Cloud zones, for example **us-west1-b**. + instance_id (str): + Required. The logical name of the Parallelstore instance in + the user project with the following restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + - Must be unique within the customer project / location + instance (google.cloud.parallelstore_v1beta.types.Instance): + Required. The instance to create. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + instance_id: str = proto.Field( + proto.STRING, + number=2, + ) + instance: "Instance" = proto.Field( + proto.MESSAGE, + number=3, + message="Instance", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateInstanceRequest(proto.Message): + r"""Message for updating a Instance + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Mask of fields to update .Field mask is used to + specify the fields to be overwritten in the Instance + resource by the update. At least one path must be supplied + in this field. The fields specified in the update_mask are + relative to the resource, not the full request. + instance (google.cloud.parallelstore_v1beta.types.Instance): + Required. The instance to update + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + instance: "Instance" = proto.Field( + proto.MESSAGE, + number=2, + message="Instance", + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteInstanceRequest(proto.Message): + r"""Message for deleting a Instance + + Attributes: + name (str): + Required. Name of the resource + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have been + cancelled successfully have [Operation.error][] value with a + [google.rpc.Status.code][google.rpc.Status.code] of 1, + corresponding to ``Code.CANCELLED``. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-parallelstore/mypy.ini b/packages/google-cloud-parallelstore/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/packages/google-cloud-parallelstore/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/packages/google-cloud-parallelstore/noxfile.py b/packages/google-cloud-parallelstore/noxfile.py new file mode 100644 index 000000000000..1e6cd48d0529 --- /dev/null +++ b/packages/google-cloud-parallelstore/noxfile.py @@ -0,0 +1,428 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2023 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 +# +# https://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 by synthtool. DO NOT EDIT! + +from __future__ import absolute_import + +import os +import pathlib +import re +import shutil +from typing import Dict, List +import warnings + +import nox + +BLACK_VERSION = "black[jupyter]==23.7.0" +ISORT_VERSION = "isort==5.11.0" + +LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] + + +DEFAULT_PYTHON_VERSION = "3.10" + +UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "asyncmock", + "pytest", + "pytest-cov", + "pytest-asyncio", +] +UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_DEPENDENCIES: List[str] = [] +UNIT_TEST_EXTRAS: List[str] = [] +UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "pytest", + "google-cloud-testutils", +] +SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_EXTRAS: List[str] = [] +SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +# 'docfx' is excluded since it only needs to run in 'docs-presubmit' +nox.options.sessions = [ + "unit", + "system", + "cover", + "lint", + "lint_setup_py", + "blacken", + "docs", +] + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *LINT_PATHS, + ) + + session.run("flake8", "google", "tests") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def format(session): + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run( + "isort", + "--fss", + *LINT_PATHS, + ) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") + + +def install_unittest_dependencies(session, *constraints): + standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES + session.install(*standard_deps, *constraints) + + if UNIT_TEST_EXTERNAL_DEPENDENCIES: + warnings.warn( + "'unit_test_external_dependencies' is deprecated. Instead, please " + "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", + DeprecationWarning, + ) + session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_LOCAL_DEPENDENCIES: + session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_EXTRAS_BY_PYTHON: + extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif UNIT_TEST_EXTRAS: + extras = UNIT_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +def default(session): + # Install all test dependencies, then install this package in-place. + + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + install_unittest_dependencies(session, "-c", constraints_path) + + # Run py.test against the unit tests. + session.run( + "py.test", + "--quiet", + f"--junitxml=unit_{session.python}_sponge_log.xml", + "--cov=google", + "--cov=tests/unit", + "--cov-append", + "--cov-config=.coveragerc", + "--cov-report=", + "--cov-fail-under=0", + os.path.join("tests", "unit"), + *session.posargs, + ) + + +@nox.session(python=UNIT_TEST_PYTHON_VERSIONS) +def unit(session): + """Run the unit test suite.""" + default(session) + + +def install_systemtest_dependencies(session, *constraints): + # Use pre-release gRPC for system tests. + # Exclude version 1.52.0rc1 which has a known issue. + # See https://github.com/grpc/grpc/issues/32163 + session.install("--pre", "grpcio!=1.52.0rc1") + + session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: + session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_LOCAL_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTRAS_BY_PYTHON: + extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif SYSTEM_TEST_EXTRAS: + extras = SYSTEM_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) +def system(session): + """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + system_test_path = os.path.join("tests", "system.py") + system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") + # Install pyopenssl for mTLS testing. + if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": + session.install("pyopenssl") + + system_test_exists = os.path.exists(system_test_path) + system_test_folder_exists = os.path.exists(system_test_folder_path) + # Sanity check: only run tests if found. + if not system_test_exists and not system_test_folder_exists: + session.skip("System tests were not found") + + install_systemtest_dependencies(session, "-c", constraints_path) + + # Run py.test against the system tests. + if system_test_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_path, + *session.posargs, + ) + if system_test_folder_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_folder_path, + *session.posargs, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "sphinx==4.5.0", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "gcp-sphinx-docfx-yaml", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python="3.12") +def prerelease_deps(session): + """Run all tests with prerelease versions of dependencies installed.""" + + # Install all dependencies + session.install("-e", ".[all, tests, tracing]") + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY + / "testing" + / f"constraints-{UNIT_TEST_PYTHON_VERSIONS[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "protobuf", + # dependency of grpc + "six", + "googleapis-common-protos", + # Exclude version 1.52.0rc1 which has a known issue. See https://github.com/grpc/grpc/issues/32163 + "grpcio!=1.52.0rc1", + "grpcio-status", + "google-api-core", + "google-auth", + "proto-plus", + "google-cloud-testutils", + # dependencies of google-cloud-testutils" + "click", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + + session.run("py.test", "tests/unit") diff --git a/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_create_instance_async.py b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_create_instance_async.py new file mode 100644 index 000000000000..000acd3e074b --- /dev/null +++ b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_create_instance_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateInstance +# 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-parallelstore + + +# [START parallelstore_v1beta_generated_Parallelstore_CreateInstance_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 parallelstore_v1beta + + +async def sample_create_instance(): + # Create a client + client = parallelstore_v1beta.ParallelstoreAsyncClient() + + # Initialize request argument(s) + instance = parallelstore_v1beta.Instance() + instance.capacity_gib = 1247 + + request = parallelstore_v1beta.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END parallelstore_v1beta_generated_Parallelstore_CreateInstance_async] diff --git a/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_create_instance_sync.py b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_create_instance_sync.py new file mode 100644 index 000000000000..73984b5ac1a5 --- /dev/null +++ b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_create_instance_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateInstance +# 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-parallelstore + + +# [START parallelstore_v1beta_generated_Parallelstore_CreateInstance_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 parallelstore_v1beta + + +def sample_create_instance(): + # Create a client + client = parallelstore_v1beta.ParallelstoreClient() + + # Initialize request argument(s) + instance = parallelstore_v1beta.Instance() + instance.capacity_gib = 1247 + + request = parallelstore_v1beta.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END parallelstore_v1beta_generated_Parallelstore_CreateInstance_sync] diff --git a/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_delete_instance_async.py b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_delete_instance_async.py new file mode 100644 index 000000000000..70fae7244908 --- /dev/null +++ b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_delete_instance_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteInstance +# 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-parallelstore + + +# [START parallelstore_v1beta_generated_Parallelstore_DeleteInstance_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 parallelstore_v1beta + + +async def sample_delete_instance(): + # Create a client + client = parallelstore_v1beta.ParallelstoreAsyncClient() + + # Initialize request argument(s) + request = parallelstore_v1beta.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END parallelstore_v1beta_generated_Parallelstore_DeleteInstance_async] diff --git a/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_delete_instance_sync.py b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_delete_instance_sync.py new file mode 100644 index 000000000000..4777b3954842 --- /dev/null +++ b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_delete_instance_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteInstance +# 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-parallelstore + + +# [START parallelstore_v1beta_generated_Parallelstore_DeleteInstance_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 parallelstore_v1beta + + +def sample_delete_instance(): + # Create a client + client = parallelstore_v1beta.ParallelstoreClient() + + # Initialize request argument(s) + request = parallelstore_v1beta.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END parallelstore_v1beta_generated_Parallelstore_DeleteInstance_sync] diff --git a/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_get_instance_async.py b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_get_instance_async.py new file mode 100644 index 000000000000..5901a2b1f803 --- /dev/null +++ b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_get_instance_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetInstance +# 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-parallelstore + + +# [START parallelstore_v1beta_generated_Parallelstore_GetInstance_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 parallelstore_v1beta + + +async def sample_get_instance(): + # Create a client + client = parallelstore_v1beta.ParallelstoreAsyncClient() + + # Initialize request argument(s) + request = parallelstore_v1beta.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_instance(request=request) + + # Handle the response + print(response) + +# [END parallelstore_v1beta_generated_Parallelstore_GetInstance_async] diff --git a/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_get_instance_sync.py b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_get_instance_sync.py new file mode 100644 index 000000000000..9881af800972 --- /dev/null +++ b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_get_instance_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetInstance +# 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-parallelstore + + +# [START parallelstore_v1beta_generated_Parallelstore_GetInstance_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 parallelstore_v1beta + + +def sample_get_instance(): + # Create a client + client = parallelstore_v1beta.ParallelstoreClient() + + # Initialize request argument(s) + request = parallelstore_v1beta.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_instance(request=request) + + # Handle the response + print(response) + +# [END parallelstore_v1beta_generated_Parallelstore_GetInstance_sync] diff --git a/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_list_instances_async.py b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_list_instances_async.py new file mode 100644 index 000000000000..3397c9fbd705 --- /dev/null +++ b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_list_instances_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListInstances +# 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-parallelstore + + +# [START parallelstore_v1beta_generated_Parallelstore_ListInstances_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 parallelstore_v1beta + + +async def sample_list_instances(): + # Create a client + client = parallelstore_v1beta.ParallelstoreAsyncClient() + + # Initialize request argument(s) + request = parallelstore_v1beta.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END parallelstore_v1beta_generated_Parallelstore_ListInstances_async] diff --git a/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_list_instances_sync.py b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_list_instances_sync.py new file mode 100644 index 000000000000..6b2436756a0e --- /dev/null +++ b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_list_instances_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListInstances +# 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-parallelstore + + +# [START parallelstore_v1beta_generated_Parallelstore_ListInstances_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 parallelstore_v1beta + + +def sample_list_instances(): + # Create a client + client = parallelstore_v1beta.ParallelstoreClient() + + # Initialize request argument(s) + request = parallelstore_v1beta.ListInstancesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_instances(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END parallelstore_v1beta_generated_Parallelstore_ListInstances_sync] diff --git a/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_update_instance_async.py b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_update_instance_async.py new file mode 100644 index 000000000000..1a50057e79a1 --- /dev/null +++ b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_update_instance_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateInstance +# 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-parallelstore + + +# [START parallelstore_v1beta_generated_Parallelstore_UpdateInstance_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 parallelstore_v1beta + + +async def sample_update_instance(): + # Create a client + client = parallelstore_v1beta.ParallelstoreAsyncClient() + + # Initialize request argument(s) + instance = parallelstore_v1beta.Instance() + instance.capacity_gib = 1247 + + request = parallelstore_v1beta.UpdateInstanceRequest( + instance=instance, + ) + + # Make the request + operation = client.update_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END parallelstore_v1beta_generated_Parallelstore_UpdateInstance_async] diff --git a/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_update_instance_sync.py b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_update_instance_sync.py new file mode 100644 index 000000000000..8df289175420 --- /dev/null +++ b/packages/google-cloud-parallelstore/samples/generated_samples/parallelstore_v1beta_generated_parallelstore_update_instance_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateInstance +# 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-parallelstore + + +# [START parallelstore_v1beta_generated_Parallelstore_UpdateInstance_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 parallelstore_v1beta + + +def sample_update_instance(): + # Create a client + client = parallelstore_v1beta.ParallelstoreClient() + + # Initialize request argument(s) + instance = parallelstore_v1beta.Instance() + instance.capacity_gib = 1247 + + request = parallelstore_v1beta.UpdateInstanceRequest( + instance=instance, + ) + + # Make the request + operation = client.update_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END parallelstore_v1beta_generated_Parallelstore_UpdateInstance_sync] diff --git a/packages/google-cloud-parallelstore/samples/generated_samples/snippet_metadata_google.cloud.parallelstore.v1beta.json b/packages/google-cloud-parallelstore/samples/generated_samples/snippet_metadata_google.cloud.parallelstore.v1beta.json new file mode 100644 index 000000000000..21ba64f1b5da --- /dev/null +++ b/packages/google-cloud-parallelstore/samples/generated_samples/snippet_metadata_google.cloud.parallelstore.v1beta.json @@ -0,0 +1,844 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.parallelstore.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-cloud-parallelstore", + "version": "0.1.1" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreAsyncClient", + "shortName": "ParallelstoreAsyncClient" + }, + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreAsyncClient.create_instance", + "method": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore.CreateInstance", + "service": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore", + "shortName": "Parallelstore" + }, + "shortName": "CreateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.parallelstore_v1beta.types.CreateInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.parallelstore_v1beta.types.Instance" + }, + { + "name": "instance_id", + "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": "create_instance" + }, + "description": "Sample for CreateInstance", + "file": "parallelstore_v1beta_generated_parallelstore_create_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "parallelstore_v1beta_generated_Parallelstore_CreateInstance_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": "parallelstore_v1beta_generated_parallelstore_create_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreClient", + "shortName": "ParallelstoreClient" + }, + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreClient.create_instance", + "method": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore.CreateInstance", + "service": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore", + "shortName": "Parallelstore" + }, + "shortName": "CreateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.parallelstore_v1beta.types.CreateInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.parallelstore_v1beta.types.Instance" + }, + { + "name": "instance_id", + "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": "create_instance" + }, + "description": "Sample for CreateInstance", + "file": "parallelstore_v1beta_generated_parallelstore_create_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "parallelstore_v1beta_generated_Parallelstore_CreateInstance_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": "parallelstore_v1beta_generated_parallelstore_create_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreAsyncClient", + "shortName": "ParallelstoreAsyncClient" + }, + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreAsyncClient.delete_instance", + "method": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore.DeleteInstance", + "service": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore", + "shortName": "Parallelstore" + }, + "shortName": "DeleteInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.parallelstore_v1beta.types.DeleteInstanceRequest" + }, + { + "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": "delete_instance" + }, + "description": "Sample for DeleteInstance", + "file": "parallelstore_v1beta_generated_parallelstore_delete_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "parallelstore_v1beta_generated_Parallelstore_DeleteInstance_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": "parallelstore_v1beta_generated_parallelstore_delete_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreClient", + "shortName": "ParallelstoreClient" + }, + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreClient.delete_instance", + "method": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore.DeleteInstance", + "service": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore", + "shortName": "Parallelstore" + }, + "shortName": "DeleteInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.parallelstore_v1beta.types.DeleteInstanceRequest" + }, + { + "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": "delete_instance" + }, + "description": "Sample for DeleteInstance", + "file": "parallelstore_v1beta_generated_parallelstore_delete_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "parallelstore_v1beta_generated_Parallelstore_DeleteInstance_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": "parallelstore_v1beta_generated_parallelstore_delete_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreAsyncClient", + "shortName": "ParallelstoreAsyncClient" + }, + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreAsyncClient.get_instance", + "method": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore.GetInstance", + "service": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore", + "shortName": "Parallelstore" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.parallelstore_v1beta.types.GetInstanceRequest" + }, + { + "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.parallelstore_v1beta.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "parallelstore_v1beta_generated_parallelstore_get_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "parallelstore_v1beta_generated_Parallelstore_GetInstance_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": "parallelstore_v1beta_generated_parallelstore_get_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreClient", + "shortName": "ParallelstoreClient" + }, + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreClient.get_instance", + "method": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore.GetInstance", + "service": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore", + "shortName": "Parallelstore" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.parallelstore_v1beta.types.GetInstanceRequest" + }, + { + "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.parallelstore_v1beta.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "parallelstore_v1beta_generated_parallelstore_get_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "parallelstore_v1beta_generated_Parallelstore_GetInstance_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": "parallelstore_v1beta_generated_parallelstore_get_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreAsyncClient", + "shortName": "ParallelstoreAsyncClient" + }, + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreAsyncClient.list_instances", + "method": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore.ListInstances", + "service": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore", + "shortName": "Parallelstore" + }, + "shortName": "ListInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.parallelstore_v1beta.types.ListInstancesRequest" + }, + { + "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.parallelstore_v1beta.services.parallelstore.pagers.ListInstancesAsyncPager", + "shortName": "list_instances" + }, + "description": "Sample for ListInstances", + "file": "parallelstore_v1beta_generated_parallelstore_list_instances_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "parallelstore_v1beta_generated_Parallelstore_ListInstances_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": "parallelstore_v1beta_generated_parallelstore_list_instances_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreClient", + "shortName": "ParallelstoreClient" + }, + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreClient.list_instances", + "method": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore.ListInstances", + "service": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore", + "shortName": "Parallelstore" + }, + "shortName": "ListInstances" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.parallelstore_v1beta.types.ListInstancesRequest" + }, + { + "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.parallelstore_v1beta.services.parallelstore.pagers.ListInstancesPager", + "shortName": "list_instances" + }, + "description": "Sample for ListInstances", + "file": "parallelstore_v1beta_generated_parallelstore_list_instances_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "parallelstore_v1beta_generated_Parallelstore_ListInstances_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": "parallelstore_v1beta_generated_parallelstore_list_instances_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreAsyncClient", + "shortName": "ParallelstoreAsyncClient" + }, + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreAsyncClient.update_instance", + "method": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore.UpdateInstance", + "service": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore", + "shortName": "Parallelstore" + }, + "shortName": "UpdateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.parallelstore_v1beta.types.UpdateInstanceRequest" + }, + { + "name": "instance", + "type": "google.cloud.parallelstore_v1beta.types.Instance" + }, + { + "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_instance" + }, + "description": "Sample for UpdateInstance", + "file": "parallelstore_v1beta_generated_parallelstore_update_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "parallelstore_v1beta_generated_Parallelstore_UpdateInstance_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "parallelstore_v1beta_generated_parallelstore_update_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreClient", + "shortName": "ParallelstoreClient" + }, + "fullName": "google.cloud.parallelstore_v1beta.ParallelstoreClient.update_instance", + "method": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore.UpdateInstance", + "service": { + "fullName": "google.cloud.parallelstore.v1beta.Parallelstore", + "shortName": "Parallelstore" + }, + "shortName": "UpdateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.parallelstore_v1beta.types.UpdateInstanceRequest" + }, + { + "name": "instance", + "type": "google.cloud.parallelstore_v1beta.types.Instance" + }, + { + "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_instance" + }, + "description": "Sample for UpdateInstance", + "file": "parallelstore_v1beta_generated_parallelstore_update_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "parallelstore_v1beta_generated_Parallelstore_UpdateInstance_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "parallelstore_v1beta_generated_parallelstore_update_instance_sync.py" + } + ] +} diff --git a/packages/google-cloud-parallelstore/scripts/decrypt-secrets.sh b/packages/google-cloud-parallelstore/scripts/decrypt-secrets.sh new file mode 100755 index 000000000000..0018b421ddf8 --- /dev/null +++ b/packages/google-cloud-parallelstore/scripts/decrypt-secrets.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# Copyright 2023 Google LLC All rights reserved. +# +# 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. + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +ROOT=$( dirname "$DIR" ) + +# Work from the project root. +cd $ROOT + +# Prevent it from overriding files. +# We recommend that sample authors use their own service account files and cloud project. +# In that case, they are supposed to prepare these files by themselves. +if [[ -f "testing/test-env.sh" ]] || \ + [[ -f "testing/service-account.json" ]] || \ + [[ -f "testing/client-secrets.json" ]]; then + echo "One or more target files exist, aborting." + exit 1 +fi + +# Use SECRET_MANAGER_PROJECT if set, fallback to cloud-devrel-kokoro-resources. +PROJECT_ID="${SECRET_MANAGER_PROJECT:-cloud-devrel-kokoro-resources}" + +gcloud secrets versions access latest --secret="python-docs-samples-test-env" \ + --project="${PROJECT_ID}" \ + > testing/test-env.sh +gcloud secrets versions access latest \ + --secret="python-docs-samples-service-account" \ + --project="${PROJECT_ID}" \ + > testing/service-account.json +gcloud secrets versions access latest \ + --secret="python-docs-samples-client-secrets" \ + --project="${PROJECT_ID}" \ + > testing/client-secrets.json diff --git a/packages/google-cloud-parallelstore/scripts/fixup_parallelstore_v1beta_keywords.py b/packages/google-cloud-parallelstore/scripts/fixup_parallelstore_v1beta_keywords.py new file mode 100644 index 000000000000..7750eb52b6f7 --- /dev/null +++ b/packages/google-cloud-parallelstore/scripts/fixup_parallelstore_v1beta_keywords.py @@ -0,0 +1,180 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class parallelstoreCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_instance': ('parent', 'instance_id', 'instance', 'request_id', ), + 'delete_instance': ('name', 'request_id', ), + 'get_instance': ('name', ), + 'list_instances': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'update_instance': ('update_mask', 'instance', 'request_id', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=parallelstoreCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the parallelstore client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/packages/google-cloud-parallelstore/setup.py b/packages/google-cloud-parallelstore/setup.py new file mode 100644 index 000000000000..ce258fe336de --- /dev/null +++ b/packages/google-cloud-parallelstore/setup.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = "google-cloud-parallelstore" + + +description = "Google Cloud Parallelstore API client library" + +version = None + +with open( + os.path.join(package_root, "google/cloud/parallelstore/gapic_version.py") +) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert len(version_candidates) == 1 + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-parallelstore" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/packages/google-cloud-parallelstore/testing/.gitignore b/packages/google-cloud-parallelstore/testing/.gitignore new file mode 100644 index 000000000000..b05fbd630881 --- /dev/null +++ b/packages/google-cloud-parallelstore/testing/.gitignore @@ -0,0 +1,3 @@ +test-env.sh +service-account.json +client-secrets.json \ No newline at end of file diff --git a/packages/google-cloud-parallelstore/testing/constraints-3.10.txt b/packages/google-cloud-parallelstore/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-cloud-parallelstore/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-cloud-parallelstore/testing/constraints-3.11.txt b/packages/google-cloud-parallelstore/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-cloud-parallelstore/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-cloud-parallelstore/testing/constraints-3.12.txt b/packages/google-cloud-parallelstore/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-cloud-parallelstore/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-cloud-parallelstore/testing/constraints-3.7.txt b/packages/google-cloud-parallelstore/testing/constraints-3.7.txt new file mode 100644 index 000000000000..b8a550c73855 --- /dev/null +++ b/packages/google-cloud-parallelstore/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.19.5 diff --git a/packages/google-cloud-parallelstore/testing/constraints-3.8.txt b/packages/google-cloud-parallelstore/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-cloud-parallelstore/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-cloud-parallelstore/testing/constraints-3.9.txt b/packages/google-cloud-parallelstore/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-cloud-parallelstore/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-cloud-parallelstore/tests/__init__.py b/packages/google-cloud-parallelstore/tests/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-cloud-parallelstore/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-cloud-parallelstore/tests/unit/__init__.py b/packages/google-cloud-parallelstore/tests/unit/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-cloud-parallelstore/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-cloud-parallelstore/tests/unit/gapic/__init__.py b/packages/google-cloud-parallelstore/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-cloud-parallelstore/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-cloud-parallelstore/tests/unit/gapic/parallelstore_v1beta/__init__.py b/packages/google-cloud-parallelstore/tests/unit/gapic/parallelstore_v1beta/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-cloud-parallelstore/tests/unit/gapic/parallelstore_v1beta/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-cloud-parallelstore/tests/unit/gapic/parallelstore_v1beta/test_parallelstore.py b/packages/google-cloud-parallelstore/tests/unit/gapic/parallelstore_v1beta/test_parallelstore.py new file mode 100644 index 000000000000..d79c6b5d6738 --- /dev/null +++ b/packages/google-cloud-parallelstore/tests/unit/gapic/parallelstore_v1beta/test_parallelstore.py @@ -0,0 +1,6240 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import Iterable +import json +import math + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import operation_async # type: ignore +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format +from google.protobuf import timestamp_pb2 # type: ignore +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +from google.cloud.parallelstore_v1beta.services.parallelstore import ( + ParallelstoreAsyncClient, + ParallelstoreClient, + pagers, + transports, +) +from google.cloud.parallelstore_v1beta.types import parallelstore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ParallelstoreClient._get_default_mtls_endpoint(None) is None + assert ( + ParallelstoreClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + ParallelstoreClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ParallelstoreClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ParallelstoreClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ParallelstoreClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +def test__read_environment_variables(): + assert ParallelstoreClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ParallelstoreClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ParallelstoreClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + ParallelstoreClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ParallelstoreClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ParallelstoreClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ParallelstoreClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ParallelstoreClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert ParallelstoreClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert ParallelstoreClient._get_client_cert_source(None, False) is None + assert ( + ParallelstoreClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + ParallelstoreClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + ParallelstoreClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + ParallelstoreClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + ParallelstoreClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ParallelstoreClient), +) +@mock.patch.object( + ParallelstoreAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ParallelstoreAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ParallelstoreClient._DEFAULT_UNIVERSE + default_endpoint = ParallelstoreClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ParallelstoreClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + ParallelstoreClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + ParallelstoreClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == ParallelstoreClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ParallelstoreClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + ParallelstoreClient._get_api_endpoint(None, None, default_universe, "always") + == ParallelstoreClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ParallelstoreClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == ParallelstoreClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ParallelstoreClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + ParallelstoreClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + ParallelstoreClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + ParallelstoreClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + ParallelstoreClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + ParallelstoreClient._get_universe_domain(None, None) + == ParallelstoreClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + ParallelstoreClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ParallelstoreClient, transports.ParallelstoreGrpcTransport, "grpc"), + (ParallelstoreClient, transports.ParallelstoreRestTransport, "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", + [ + (ParallelstoreClient, "grpc"), + (ParallelstoreAsyncClient, "grpc_asyncio"), + (ParallelstoreClient, "rest"), + ], +) +def test_parallelstore_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "parallelstore.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://parallelstore.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.ParallelstoreGrpcTransport, "grpc"), + (transports.ParallelstoreGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ParallelstoreRestTransport, "rest"), + ], +) +def test_parallelstore_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ParallelstoreClient, "grpc"), + (ParallelstoreAsyncClient, "grpc_asyncio"), + (ParallelstoreClient, "rest"), + ], +) +def test_parallelstore_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "parallelstore.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://parallelstore.googleapis.com" + ) + + +def test_parallelstore_client_get_transport_class(): + transport = ParallelstoreClient.get_transport_class() + available_transports = [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreRestTransport, + ] + assert transport in available_transports + + transport = ParallelstoreClient.get_transport_class("grpc") + assert transport == transports.ParallelstoreGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ParallelstoreClient, transports.ParallelstoreGrpcTransport, "grpc"), + ( + ParallelstoreAsyncClient, + transports.ParallelstoreGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (ParallelstoreClient, transports.ParallelstoreRestTransport, "rest"), + ], +) +@mock.patch.object( + ParallelstoreClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ParallelstoreClient), +) +@mock.patch.object( + ParallelstoreAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ParallelstoreAsyncClient), +) +def test_parallelstore_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ParallelstoreClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(ParallelstoreClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ParallelstoreClient, transports.ParallelstoreGrpcTransport, "grpc", "true"), + ( + ParallelstoreAsyncClient, + transports.ParallelstoreGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ParallelstoreClient, transports.ParallelstoreGrpcTransport, "grpc", "false"), + ( + ParallelstoreAsyncClient, + transports.ParallelstoreGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (ParallelstoreClient, transports.ParallelstoreRestTransport, "rest", "true"), + (ParallelstoreClient, transports.ParallelstoreRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + ParallelstoreClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ParallelstoreClient), +) +@mock.patch.object( + ParallelstoreAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ParallelstoreAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_parallelstore_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [ParallelstoreClient, ParallelstoreAsyncClient] +) +@mock.patch.object( + ParallelstoreClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ParallelstoreClient), +) +@mock.patch.object( + ParallelstoreAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ParallelstoreAsyncClient), +) +def test_parallelstore_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize( + "client_class", [ParallelstoreClient, ParallelstoreAsyncClient] +) +@mock.patch.object( + ParallelstoreClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ParallelstoreClient), +) +@mock.patch.object( + ParallelstoreAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ParallelstoreAsyncClient), +) +def test_parallelstore_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ParallelstoreClient._DEFAULT_UNIVERSE + default_endpoint = ParallelstoreClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ParallelstoreClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ParallelstoreClient, transports.ParallelstoreGrpcTransport, "grpc"), + ( + ParallelstoreAsyncClient, + transports.ParallelstoreGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (ParallelstoreClient, transports.ParallelstoreRestTransport, "rest"), + ], +) +def test_parallelstore_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + ParallelstoreClient, + transports.ParallelstoreGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + ParallelstoreAsyncClient, + transports.ParallelstoreGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (ParallelstoreClient, transports.ParallelstoreRestTransport, "rest", None), + ], +) +def test_parallelstore_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_parallelstore_client_client_options_from_dict(): + with mock.patch( + "google.cloud.parallelstore_v1beta.services.parallelstore.transports.ParallelstoreGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ParallelstoreClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + ParallelstoreClient, + transports.ParallelstoreGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + ParallelstoreAsyncClient, + transports.ParallelstoreGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_parallelstore_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "parallelstore.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="parallelstore.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.ListInstancesRequest, + dict, + ], +) +def test_list_instances(request_type, transport: str = "grpc"): + client = ParallelstoreClient( + 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_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = parallelstore.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == parallelstore.ListInstancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_instances_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + client.list_instances() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == parallelstore.ListInstancesRequest() + + +@pytest.mark.asyncio +async def test_list_instances_async( + transport: str = "grpc_asyncio", request_type=parallelstore.ListInstancesRequest +): + client = ParallelstoreAsyncClient( + 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_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + parallelstore.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == parallelstore.ListInstancesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_instances_async_from_dict(): + await test_list_instances_async(request_type=dict) + + +def test_list_instances_field_headers(): + client = ParallelstoreClient( + 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 = parallelstore.ListInstancesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + call.return_value = parallelstore.ListInstancesResponse() + client.list_instances(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_instances_field_headers_async(): + client = ParallelstoreAsyncClient( + 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 = parallelstore.ListInstancesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + parallelstore.ListInstancesResponse() + ) + await client.list_instances(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_instances_flattened(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = parallelstore.ListInstancesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_instances( + 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_instances_flattened_error(): + client = ParallelstoreClient( + 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_instances( + parallelstore.ListInstancesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_instances_flattened_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = parallelstore.ListInstancesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + parallelstore.ListInstancesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_instances( + 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_instances_flattened_error_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_instances( + parallelstore.ListInstancesRequest(), + parent="parent_value", + ) + + +def test_list_instances_pager(transport_name: str = "grpc"): + client = ParallelstoreClient( + 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_instances), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + parallelstore.ListInstancesResponse( + instances=[ + parallelstore.Instance(), + parallelstore.Instance(), + parallelstore.Instance(), + ], + next_page_token="abc", + ), + parallelstore.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + parallelstore.ListInstancesResponse( + instances=[ + parallelstore.Instance(), + ], + next_page_token="ghi", + ), + parallelstore.ListInstancesResponse( + instances=[ + parallelstore.Instance(), + parallelstore.Instance(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_instances(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, parallelstore.Instance) for i in results) + + +def test_list_instances_pages(transport_name: str = "grpc"): + client = ParallelstoreClient( + 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_instances), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + parallelstore.ListInstancesResponse( + instances=[ + parallelstore.Instance(), + parallelstore.Instance(), + parallelstore.Instance(), + ], + next_page_token="abc", + ), + parallelstore.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + parallelstore.ListInstancesResponse( + instances=[ + parallelstore.Instance(), + ], + next_page_token="ghi", + ), + parallelstore.ListInstancesResponse( + instances=[ + parallelstore.Instance(), + parallelstore.Instance(), + ], + ), + RuntimeError, + ) + pages = list(client.list_instances(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_instances_async_pager(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + parallelstore.ListInstancesResponse( + instances=[ + parallelstore.Instance(), + parallelstore.Instance(), + parallelstore.Instance(), + ], + next_page_token="abc", + ), + parallelstore.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + parallelstore.ListInstancesResponse( + instances=[ + parallelstore.Instance(), + ], + next_page_token="ghi", + ), + parallelstore.ListInstancesResponse( + instances=[ + parallelstore.Instance(), + parallelstore.Instance(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_instances( + 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, parallelstore.Instance) for i in responses) + + +@pytest.mark.asyncio +async def test_list_instances_async_pages(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + parallelstore.ListInstancesResponse( + instances=[ + parallelstore.Instance(), + parallelstore.Instance(), + parallelstore.Instance(), + ], + next_page_token="abc", + ), + parallelstore.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + parallelstore.ListInstancesResponse( + instances=[ + parallelstore.Instance(), + ], + next_page_token="ghi", + ), + parallelstore.ListInstancesResponse( + instances=[ + parallelstore.Instance(), + parallelstore.Instance(), + ], + ), + 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_instances(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", + [ + parallelstore.GetInstanceRequest, + dict, + ], +) +def test_get_instance(request_type, transport: str = "grpc"): + client = ParallelstoreClient( + 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_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = parallelstore.Instance( + name="name_value", + description="description_value", + state=parallelstore.Instance.State.CREATING, + capacity_gib=1247, + daos_version="daos_version_value", + access_points=["access_points_value"], + network="network_value", + reserved_ip_range="reserved_ip_range_value", + ) + response = client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == parallelstore.GetInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, parallelstore.Instance) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == parallelstore.Instance.State.CREATING + assert response.capacity_gib == 1247 + assert response.daos_version == "daos_version_value" + assert response.access_points == ["access_points_value"] + assert response.network == "network_value" + assert response.reserved_ip_range == "reserved_ip_range_value" + + +def test_get_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + client.get_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == parallelstore.GetInstanceRequest() + + +@pytest.mark.asyncio +async def test_get_instance_async( + transport: str = "grpc_asyncio", request_type=parallelstore.GetInstanceRequest +): + client = ParallelstoreAsyncClient( + 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_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + parallelstore.Instance( + name="name_value", + description="description_value", + state=parallelstore.Instance.State.CREATING, + capacity_gib=1247, + daos_version="daos_version_value", + access_points=["access_points_value"], + network="network_value", + reserved_ip_range="reserved_ip_range_value", + ) + ) + response = await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == parallelstore.GetInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, parallelstore.Instance) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == parallelstore.Instance.State.CREATING + assert response.capacity_gib == 1247 + assert response.daos_version == "daos_version_value" + assert response.access_points == ["access_points_value"] + assert response.network == "network_value" + assert response.reserved_ip_range == "reserved_ip_range_value" + + +@pytest.mark.asyncio +async def test_get_instance_async_from_dict(): + await test_get_instance_async(request_type=dict) + + +def test_get_instance_field_headers(): + client = ParallelstoreClient( + 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 = parallelstore.GetInstanceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + call.return_value = parallelstore.Instance() + client.get_instance(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_instance_field_headers_async(): + client = ParallelstoreAsyncClient( + 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 = parallelstore.GetInstanceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + parallelstore.Instance() + ) + await client.get_instance(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_instance_flattened(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = parallelstore.Instance() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_instance( + 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_instance_flattened_error(): + client = ParallelstoreClient( + 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_instance( + parallelstore.GetInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_instance_flattened_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = parallelstore.Instance() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + parallelstore.Instance() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_instance( + 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_instance_flattened_error_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_instance( + parallelstore.GetInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.CreateInstanceRequest, + dict, + ], +) +def test_create_instance(request_type, transport: str = "grpc"): + client = ParallelstoreClient( + 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_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == parallelstore.CreateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + client.create_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == parallelstore.CreateInstanceRequest() + + +@pytest.mark.asyncio +async def test_create_instance_async( + transport: str = "grpc_asyncio", request_type=parallelstore.CreateInstanceRequest +): + client = ParallelstoreAsyncClient( + 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_instance), "__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_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == parallelstore.CreateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_instance_async_from_dict(): + await test_create_instance_async(request_type=dict) + + +def test_create_instance_field_headers(): + client = ParallelstoreClient( + 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 = parallelstore.CreateInstanceRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_instance(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_instance_field_headers_async(): + client = ParallelstoreAsyncClient( + 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 = parallelstore.CreateInstanceRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_instance(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_instance_flattened(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__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_instance( + parent="parent_value", + instance=parallelstore.Instance(name="name_value"), + instance_id="instance_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].instance + mock_val = parallelstore.Instance(name="name_value") + assert arg == mock_val + arg = args[0].instance_id + mock_val = "instance_id_value" + assert arg == mock_val + + +def test_create_instance_flattened_error(): + client = ParallelstoreClient( + 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_instance( + parallelstore.CreateInstanceRequest(), + parent="parent_value", + instance=parallelstore.Instance(name="name_value"), + instance_id="instance_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_instance_flattened_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__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_instance( + parent="parent_value", + instance=parallelstore.Instance(name="name_value"), + instance_id="instance_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].instance + mock_val = parallelstore.Instance(name="name_value") + assert arg == mock_val + arg = args[0].instance_id + mock_val = "instance_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_instance_flattened_error_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_instance( + parallelstore.CreateInstanceRequest(), + parent="parent_value", + instance=parallelstore.Instance(name="name_value"), + instance_id="instance_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.UpdateInstanceRequest, + dict, + ], +) +def test_update_instance(request_type, transport: str = "grpc"): + client = ParallelstoreClient( + 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_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == parallelstore.UpdateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + client.update_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == parallelstore.UpdateInstanceRequest() + + +@pytest.mark.asyncio +async def test_update_instance_async( + transport: str = "grpc_asyncio", request_type=parallelstore.UpdateInstanceRequest +): + client = ParallelstoreAsyncClient( + 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_instance), "__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_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == parallelstore.UpdateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_instance_async_from_dict(): + await test_update_instance_async(request_type=dict) + + +def test_update_instance_field_headers(): + client = ParallelstoreClient( + 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 = parallelstore.UpdateInstanceRequest() + + request.instance.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_instance(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", + "instance.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_instance_field_headers_async(): + client = ParallelstoreAsyncClient( + 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 = parallelstore.UpdateInstanceRequest() + + request.instance.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_instance(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", + "instance.name=name_value", + ) in kw["metadata"] + + +def test_update_instance_flattened(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__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_instance( + instance=parallelstore.Instance(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].instance + mock_val = parallelstore.Instance(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_instance_flattened_error(): + client = ParallelstoreClient( + 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_instance( + parallelstore.UpdateInstanceRequest(), + instance=parallelstore.Instance(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_instance_flattened_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__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_instance( + instance=parallelstore.Instance(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].instance + mock_val = parallelstore.Instance(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_instance_flattened_error_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_instance( + parallelstore.UpdateInstanceRequest(), + instance=parallelstore.Instance(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.DeleteInstanceRequest, + dict, + ], +) +def test_delete_instance(request_type, transport: str = "grpc"): + client = ParallelstoreClient( + 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_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == parallelstore.DeleteInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_instance_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + client.delete_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == parallelstore.DeleteInstanceRequest() + + +@pytest.mark.asyncio +async def test_delete_instance_async( + transport: str = "grpc_asyncio", request_type=parallelstore.DeleteInstanceRequest +): + client = ParallelstoreAsyncClient( + 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_instance), "__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_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == parallelstore.DeleteInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_instance_async_from_dict(): + await test_delete_instance_async(request_type=dict) + + +def test_delete_instance_field_headers(): + client = ParallelstoreClient( + 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 = parallelstore.DeleteInstanceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_instance(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_instance_field_headers_async(): + client = ParallelstoreAsyncClient( + 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 = parallelstore.DeleteInstanceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_instance(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_instance_flattened(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__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_instance( + 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_delete_instance_flattened_error(): + client = ParallelstoreClient( + 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_instance( + parallelstore.DeleteInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_instance_flattened_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__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_instance( + 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_instance_flattened_error_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_instance( + parallelstore.DeleteInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.ListInstancesRequest, + dict, + ], +) +def test_list_instances_rest(request_type): + client = ParallelstoreClient( + 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 = parallelstore.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = parallelstore.ListInstancesResponse.pb(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_instances(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_instances_rest_required_fields( + request_type=parallelstore.ListInstancesRequest, +): + transport_class = transports.ParallelstoreRestTransport + + 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_instances._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_instances._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 = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = parallelstore.ListInstancesResponse() + # 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 = parallelstore.ListInstancesResponse.pb(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_instances(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_instances_rest_unset_required_fields(): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_instances._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_instances_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(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.ParallelstoreRestInterceptor, "post_list_instances" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_list_instances" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.ListInstancesRequest.pb( + parallelstore.ListInstancesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = parallelstore.ListInstancesResponse.to_json( + parallelstore.ListInstancesResponse() + ) + + request = parallelstore.ListInstancesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = parallelstore.ListInstancesResponse() + + client.list_instances( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_instances_rest_bad_request( + transport: str = "rest", request_type=parallelstore.ListInstancesRequest +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_instances(request) + + +def test_list_instances_rest_flattened(): + client = ParallelstoreClient( + 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 = parallelstore.ListInstancesResponse() + + # 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 = parallelstore.ListInstancesResponse.pb(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_instances(**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/*}/instances" + % client.transport._host, + args[1], + ) + + +def test_list_instances_rest_flattened_error(transport: str = "rest"): + client = ParallelstoreClient( + 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_instances( + parallelstore.ListInstancesRequest(), + parent="parent_value", + ) + + +def test_list_instances_rest_pager(transport: str = "rest"): + client = ParallelstoreClient( + 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 = ( + parallelstore.ListInstancesResponse( + instances=[ + parallelstore.Instance(), + parallelstore.Instance(), + parallelstore.Instance(), + ], + next_page_token="abc", + ), + parallelstore.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + parallelstore.ListInstancesResponse( + instances=[ + parallelstore.Instance(), + ], + next_page_token="ghi", + ), + parallelstore.ListInstancesResponse( + instances=[ + parallelstore.Instance(), + parallelstore.Instance(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + parallelstore.ListInstancesResponse.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_instances(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, parallelstore.Instance) for i in results) + + pages = list(client.list_instances(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.GetInstanceRequest, + dict, + ], +) +def test_get_instance_rest(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = parallelstore.Instance( + name="name_value", + description="description_value", + state=parallelstore.Instance.State.CREATING, + capacity_gib=1247, + daos_version="daos_version_value", + access_points=["access_points_value"], + network="network_value", + reserved_ip_range="reserved_ip_range_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 = parallelstore.Instance.pb(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_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, parallelstore.Instance) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == parallelstore.Instance.State.CREATING + assert response.capacity_gib == 1247 + assert response.daos_version == "daos_version_value" + assert response.access_points == ["access_points_value"] + assert response.network == "network_value" + assert response.reserved_ip_range == "reserved_ip_range_value" + + +def test_get_instance_rest_required_fields( + request_type=parallelstore.GetInstanceRequest, +): + transport_class = transports.ParallelstoreRestTransport + + 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_instance._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_instance._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 = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = parallelstore.Instance() + # 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 = parallelstore.Instance.pb(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_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_instance_rest_unset_required_fields(): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(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.ParallelstoreRestInterceptor, "post_get_instance" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_get_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.GetInstanceRequest.pb( + parallelstore.GetInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = parallelstore.Instance.to_json( + parallelstore.Instance() + ) + + request = parallelstore.GetInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = parallelstore.Instance() + + client.get_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_instance_rest_bad_request( + transport: str = "rest", request_type=parallelstore.GetInstanceRequest +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_instance(request) + + +def test_get_instance_rest_flattened(): + client = ParallelstoreClient( + 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 = parallelstore.Instance() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/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 = parallelstore.Instance.pb(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_instance(**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/*/instances/*}" + % client.transport._host, + args[1], + ) + + +def test_get_instance_rest_flattened_error(transport: str = "rest"): + client = ParallelstoreClient( + 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_instance( + parallelstore.GetInstanceRequest(), + name="name_value", + ) + + +def test_get_instance_rest_error(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.CreateInstanceRequest, + dict, + ], +) +def test_create_instance_rest(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["instance"] = { + "name": "name_value", + "description": "description_value", + "state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "capacity_gib": 1247, + "daos_version": "daos_version_value", + "access_points": ["access_points_value1", "access_points_value2"], + "network": "network_value", + "reserved_ip_range": "reserved_ip_range_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 = parallelstore.CreateInstanceRequest.meta.fields["instance"] + + 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["instance"].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["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][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 = 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_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_instance_rest_required_fields( + request_type=parallelstore.CreateInstanceRequest, +): + transport_class = transports.ParallelstoreRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["instance_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 "instanceId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["instanceId"] = "instance_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "instance_id", + "request_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 "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == "instance_id_value" + + client = ParallelstoreClient( + 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_instance(request) + + expected_params = [ + ( + "instanceId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_instance_rest_unset_required_fields(): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_instance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "instanceId", + "requestId", + ) + ) + & set( + ( + "parent", + "instanceId", + "instance", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_instance_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(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.ParallelstoreRestInterceptor, "post_create_instance" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_create_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.CreateInstanceRequest.pb( + parallelstore.CreateInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = parallelstore.CreateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_instance_rest_bad_request( + transport: str = "rest", request_type=parallelstore.CreateInstanceRequest +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_instance(request) + + +def test_create_instance_rest_flattened(): + client = ParallelstoreClient( + 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", + instance=parallelstore.Instance(name="name_value"), + instance_id="instance_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_instance(**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/*}/instances" + % client.transport._host, + args[1], + ) + + +def test_create_instance_rest_flattened_error(transport: str = "rest"): + client = ParallelstoreClient( + 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_instance( + parallelstore.CreateInstanceRequest(), + parent="parent_value", + instance=parallelstore.Instance(name="name_value"), + instance_id="instance_id_value", + ) + + +def test_create_instance_rest_error(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.UpdateInstanceRequest, + dict, + ], +) +def test_update_instance_rest(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + } + request_init["instance"] = { + "name": "projects/sample1/locations/sample2/instances/sample3", + "description": "description_value", + "state": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "capacity_gib": 1247, + "daos_version": "daos_version_value", + "access_points": ["access_points_value1", "access_points_value2"], + "network": "network_value", + "reserved_ip_range": "reserved_ip_range_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 = parallelstore.UpdateInstanceRequest.meta.fields["instance"] + + 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["instance"].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["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][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 = 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_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_instance_rest_required_fields( + request_type=parallelstore.UpdateInstanceRequest, +): + transport_class = transports.ParallelstoreRestTransport + + 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_instance._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_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ParallelstoreClient( + 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_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_instance_rest_unset_required_fields(): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_instance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "updateMask", + "instance", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_instance_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(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.ParallelstoreRestInterceptor, "post_update_instance" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_update_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.UpdateInstanceRequest.pb( + parallelstore.UpdateInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = parallelstore.UpdateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_instance_rest_bad_request( + transport: str = "rest", request_type=parallelstore.UpdateInstanceRequest +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "instance": {"name": "projects/sample1/locations/sample2/instances/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_instance(request) + + +def test_update_instance_rest_flattened(): + client = ParallelstoreClient( + 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 = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + instance=parallelstore.Instance(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_instance(**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/{instance.name=projects/*/locations/*/instances/*}" + % client.transport._host, + args[1], + ) + + +def test_update_instance_rest_flattened_error(transport: str = "rest"): + client = ParallelstoreClient( + 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_instance( + parallelstore.UpdateInstanceRequest(), + instance=parallelstore.Instance(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_instance_rest_error(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + parallelstore.DeleteInstanceRequest, + dict, + ], +) +def test_delete_instance_rest(request_type): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = 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_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_instance_rest_required_fields( + request_type=parallelstore.DeleteInstanceRequest, +): + transport_class = transports.ParallelstoreRestTransport + + 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_instance._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_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = ParallelstoreClient( + 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_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_instance_rest_unset_required_fields(): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_instance_rest_interceptors(null_interceptor): + transport = transports.ParallelstoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ParallelstoreRestInterceptor(), + ) + client = ParallelstoreClient(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.ParallelstoreRestInterceptor, "post_delete_instance" + ) as post, mock.patch.object( + transports.ParallelstoreRestInterceptor, "pre_delete_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = parallelstore.DeleteInstanceRequest.pb( + parallelstore.DeleteInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = parallelstore.DeleteInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_instance_rest_bad_request( + transport: str = "rest", request_type=parallelstore.DeleteInstanceRequest +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_instance(request) + + +def test_delete_instance_rest_flattened(): + client = ParallelstoreClient( + 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/instances/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_instance(**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/*/instances/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_instance_rest_flattened_error(transport: str = "rest"): + client = ParallelstoreClient( + 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_instance( + parallelstore.DeleteInstanceRequest(), + name="name_value", + ) + + +def test_delete_instance_rest_error(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ParallelstoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ParallelstoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ParallelstoreClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ParallelstoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ParallelstoreClient( + 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 = ParallelstoreClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ParallelstoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ParallelstoreClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ParallelstoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ParallelstoreClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ParallelstoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ParallelstoreGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreGrpcAsyncIOTransport, + transports.ParallelstoreRestTransport, + ], +) +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() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = ParallelstoreClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ParallelstoreGrpcTransport, + ) + + +def test_parallelstore_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ParallelstoreTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_parallelstore_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.parallelstore_v1beta.services.parallelstore.transports.ParallelstoreTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ParallelstoreTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_instances", + "get_instance", + "create_instance", + "update_instance", + "delete_instance", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_parallelstore_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.parallelstore_v1beta.services.parallelstore.transports.ParallelstoreTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ParallelstoreTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_parallelstore_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.parallelstore_v1beta.services.parallelstore.transports.ParallelstoreTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ParallelstoreTransport() + adc.assert_called_once() + + +def test_parallelstore_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ParallelstoreClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreGrpcAsyncIOTransport, + ], +) +def test_parallelstore_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreGrpcAsyncIOTransport, + transports.ParallelstoreRestTransport, + ], +) +def test_parallelstore_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParallelstoreGrpcTransport, grpc_helpers), + (transports.ParallelstoreGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_parallelstore_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "parallelstore.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="parallelstore.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreGrpcAsyncIOTransport, + ], +) +def test_parallelstore_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_parallelstore_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.ParallelstoreRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_parallelstore_rest_lro_client(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_parallelstore_host_no_port(transport_name): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="parallelstore.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "parallelstore.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://parallelstore.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_parallelstore_host_with_port(transport_name): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="parallelstore.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "parallelstore.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://parallelstore.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_parallelstore_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ParallelstoreClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ParallelstoreClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_instances._session + session2 = client2.transport.list_instances._session + assert session1 != session2 + session1 = client1.transport.get_instance._session + session2 = client2.transport.get_instance._session + assert session1 != session2 + session1 = client1.transport.create_instance._session + session2 = client2.transport.create_instance._session + assert session1 != session2 + session1 = client1.transport.update_instance._session + session2 = client2.transport.update_instance._session + assert session1 != session2 + session1 = client1.transport.delete_instance._session + session2 = client2.transport.delete_instance._session + assert session1 != session2 + + +def test_parallelstore_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ParallelstoreGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_parallelstore_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ParallelstoreGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreGrpcAsyncIOTransport, + ], +) +def test_parallelstore_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParallelstoreGrpcTransport, + transports.ParallelstoreGrpcAsyncIOTransport, + ], +) +def test_parallelstore_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_parallelstore_grpc_lro_client(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_parallelstore_grpc_lro_async_client(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_address_path(): + project = "squid" + region = "clam" + address = "whelk" + expected = "projects/{project}/regions/{region}/addresses/{address}".format( + project=project, + region=region, + address=address, + ) + actual = ParallelstoreClient.address_path(project, region, address) + assert expected == actual + + +def test_parse_address_path(): + expected = { + "project": "octopus", + "region": "oyster", + "address": "nudibranch", + } + path = ParallelstoreClient.address_path(**expected) + + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_address_path(path) + assert expected == actual + + +def test_instance_path(): + project = "cuttlefish" + location = "mussel" + instance = "winkle" + expected = "projects/{project}/locations/{location}/instances/{instance}".format( + project=project, + location=location, + instance=instance, + ) + actual = ParallelstoreClient.instance_path(project, location, instance) + assert expected == actual + + +def test_parse_instance_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "instance": "abalone", + } + path = ParallelstoreClient.instance_path(**expected) + + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_instance_path(path) + assert expected == actual + + +def test_network_path(): + project = "squid" + network = "clam" + expected = "projects/{project}/global/networks/{network}".format( + project=project, + network=network, + ) + actual = ParallelstoreClient.network_path(project, network) + assert expected == actual + + +def test_parse_network_path(): + expected = { + "project": "whelk", + "network": "octopus", + } + path = ParallelstoreClient.network_path(**expected) + + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_network_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ParallelstoreClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = ParallelstoreClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ParallelstoreClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = ParallelstoreClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = ParallelstoreClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = ParallelstoreClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format( + project=project, + ) + actual = ParallelstoreClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = ParallelstoreClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = ParallelstoreClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = ParallelstoreClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ParallelstoreClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.ParallelstoreTransport, "_prep_wrapped_messages" + ) as prep: + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ParallelstoreTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ParallelstoreClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_location_rest_bad_request( + transport: str = "rest", request_type=locations_pb2.GetLocationRequest +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + 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 = ParallelstoreClient( + 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(type(client.transport._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 = 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.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( + transport: str = "rest", request_type=locations_pb2.ListLocationsRequest +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + 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 = ParallelstoreClient( + 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(type(client.transport._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 = 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.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.CancelOperationRequest +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = ParallelstoreClient( + 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(type(client.transport._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 = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = ParallelstoreClient( + 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(type(client.transport._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 = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + 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( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ParallelstoreClient( + 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(type(client.transport._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 = 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.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.ListOperationsRequest +): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ParallelstoreClient( + 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(type(client.transport._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 = 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.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = ParallelstoreClient( + 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 = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(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 response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = ParallelstoreAsyncClient( + 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 = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(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 response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = ParallelstoreClient( + 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 = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(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=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = ParallelstoreAsyncClient( + 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 = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(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=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = ParallelstoreClient( + 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 = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(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 response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = ParallelstoreAsyncClient( + 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 = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(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 response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = ParallelstoreClient( + 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 = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(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=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = ParallelstoreAsyncClient( + 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 = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(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=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = ParallelstoreClient( + 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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(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 response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = ParallelstoreAsyncClient( + 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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(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 response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = ParallelstoreClient( + 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 = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(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=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = ParallelstoreAsyncClient( + 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 = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(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=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = ParallelstoreClient( + 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 = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(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 response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = ParallelstoreAsyncClient( + 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 = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(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 response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = ParallelstoreClient( + 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 = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(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=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = ParallelstoreAsyncClient( + 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 = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(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=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = ParallelstoreClient( + 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 = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(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 response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = ParallelstoreAsyncClient( + 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 = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(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 response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = ParallelstoreClient( + 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 = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(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=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = ParallelstoreAsyncClient( + 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 = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(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=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = ParallelstoreClient( + 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 = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(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 response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = ParallelstoreAsyncClient( + 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 = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(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 response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = ParallelstoreClient(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 = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(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=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = ParallelstoreAsyncClient(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 = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(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=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = ParallelstoreAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = ParallelstoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (ParallelstoreClient, transports.ParallelstoreGrpcTransport), + (ParallelstoreAsyncClient, transports.ParallelstoreGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-phishing-protection/CHANGELOG.md b/packages/google-cloud-phishing-protection/CHANGELOG.md index bb75976120b7..4c10d73de52b 100644 --- a/packages/google-cloud-phishing-protection/CHANGELOG.md +++ b/packages/google-cloud-phishing-protection/CHANGELOG.md @@ -5,6 +5,13 @@ [1]: https://pypi.org/project/google-cloud-phishing-protection/#history +## [1.11.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-phishing-protection-v1.11.2...google-cloud-phishing-protection-v1.11.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [1.11.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-phishing-protection-v1.11.1...google-cloud-phishing-protection-v1.11.2) (2024-02-22) diff --git a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection/gapic_version.py b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection/gapic_version.py index 787a045996f3..88fbabfeb794 100644 --- a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection/gapic_version.py +++ b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.11.2" # {x-release-please-version} +__version__ = "1.11.3" # {x-release-please-version} diff --git a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/gapic_version.py b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/gapic_version.py index 787a045996f3..88fbabfeb794 100644 --- a/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_v1beta1/gapic_version.py +++ b/packages/google-cloud-phishing-protection/google/cloud/phishingprotection_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.2" # {x-release-please-version} +__version__ = "1.11.3" # {x-release-please-version} diff --git a/packages/google-cloud-phishing-protection/samples/generated_samples/snippet_metadata_google.cloud.phishingprotection.v1beta1.json b/packages/google-cloud-phishing-protection/samples/generated_samples/snippet_metadata_google.cloud.phishingprotection.v1beta1.json index 5523c299e45e..2e8d88c9c5ad 100644 --- a/packages/google-cloud-phishing-protection/samples/generated_samples/snippet_metadata_google.cloud.phishingprotection.v1beta1.json +++ b/packages/google-cloud-phishing-protection/samples/generated_samples/snippet_metadata_google.cloud.phishingprotection.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-phishing-protection", - "version": "1.11.2" + "version": "1.11.3" }, "snippets": [ { diff --git a/packages/google-cloud-phishing-protection/setup.py b/packages/google-cloud-phishing-protection/setup.py index e58192f57bdf..65bb2800a93a 100644 --- a/packages/google-cloud-phishing-protection/setup.py +++ b/packages/google-cloud-phishing-protection/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-policy-troubleshooter/CHANGELOG.md b/packages/google-cloud-policy-troubleshooter/CHANGELOG.md index c7c671632725..d6efbc218f80 100644 --- a/packages/google-cloud-policy-troubleshooter/CHANGELOG.md +++ b/packages/google-cloud-policy-troubleshooter/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.11.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-policy-troubleshooter-v1.11.2...google-cloud-policy-troubleshooter-v1.11.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [1.11.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-policy-troubleshooter-v1.11.1...google-cloud-policy-troubleshooter-v1.11.2) (2024-02-22) diff --git a/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter/gapic_version.py b/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter/gapic_version.py index 787a045996f3..88fbabfeb794 100644 --- a/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter/gapic_version.py +++ b/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.11.2" # {x-release-please-version} +__version__ = "1.11.3" # {x-release-please-version} diff --git a/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/gapic_version.py b/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/gapic_version.py index 787a045996f3..88fbabfeb794 100644 --- a/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_v1/gapic_version.py +++ b/packages/google-cloud-policy-troubleshooter/google/cloud/policytroubleshooter_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.2" # {x-release-please-version} +__version__ = "1.11.3" # {x-release-please-version} diff --git a/packages/google-cloud-policy-troubleshooter/samples/generated_samples/snippet_metadata_google.cloud.policytroubleshooter.v1.json b/packages/google-cloud-policy-troubleshooter/samples/generated_samples/snippet_metadata_google.cloud.policytroubleshooter.v1.json index 3fc2f0a14482..14702a18c0b4 100644 --- a/packages/google-cloud-policy-troubleshooter/samples/generated_samples/snippet_metadata_google.cloud.policytroubleshooter.v1.json +++ b/packages/google-cloud-policy-troubleshooter/samples/generated_samples/snippet_metadata_google.cloud.policytroubleshooter.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-policy-troubleshooter", - "version": "1.11.2" + "version": "1.11.3" }, "snippets": [ { diff --git a/packages/google-cloud-policy-troubleshooter/setup.py b/packages/google-cloud-policy-troubleshooter/setup.py index 789f789563e0..ba363ac6012b 100644 --- a/packages/google-cloud-policy-troubleshooter/setup.py +++ b/packages/google-cloud-policy-troubleshooter/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-policysimulator/CHANGELOG.md b/packages/google-cloud-policysimulator/CHANGELOG.md index 37ef9ecb1172..1784ccd2db9a 100644 --- a/packages/google-cloud-policysimulator/CHANGELOG.md +++ b/packages/google-cloud-policysimulator/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-policysimulator-v0.1.5...google-cloud-policysimulator-v0.1.6) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [0.1.5](https://github.com/googleapis/google-cloud-python/compare/google-cloud-policysimulator-v0.1.4...google-cloud-policysimulator-v0.1.5) (2024-02-22) diff --git a/packages/google-cloud-policysimulator/google/cloud/policysimulator/gapic_version.py b/packages/google-cloud-policysimulator/google/cloud/policysimulator/gapic_version.py index ae12f4dfd596..60402a4567d1 100644 --- a/packages/google-cloud-policysimulator/google/cloud/policysimulator/gapic_version.py +++ b/packages/google-cloud-policysimulator/google/cloud/policysimulator/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-policysimulator/google/cloud/policysimulator_v1/gapic_version.py b/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/gapic_version.py index ae12f4dfd596..60402a4567d1 100644 --- a/packages/google-cloud-policysimulator/google/cloud/policysimulator_v1/gapic_version.py +++ b/packages/google-cloud-policysimulator/google/cloud/policysimulator_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-policysimulator/samples/generated_samples/snippet_metadata_google.cloud.policysimulator.v1.json b/packages/google-cloud-policysimulator/samples/generated_samples/snippet_metadata_google.cloud.policysimulator.v1.json index fea7a1a7a556..aa78da2801dd 100644 --- a/packages/google-cloud-policysimulator/samples/generated_samples/snippet_metadata_google.cloud.policysimulator.v1.json +++ b/packages/google-cloud-policysimulator/samples/generated_samples/snippet_metadata_google.cloud.policysimulator.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-policysimulator", - "version": "0.1.5" + "version": "0.1.6" }, "snippets": [ { diff --git a/packages/google-cloud-policysimulator/setup.py b/packages/google-cloud-policysimulator/setup.py index 37fde01ffa3a..565f50f4c708 100644 --- a/packages/google-cloud-policysimulator/setup.py +++ b/packages/google-cloud-policysimulator/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-policytroubleshooter-iam/CHANGELOG.md b/packages/google-cloud-policytroubleshooter-iam/CHANGELOG.md index 4b8275f3c448..b9af63ad7e47 100644 --- a/packages/google-cloud-policytroubleshooter-iam/CHANGELOG.md +++ b/packages/google-cloud-policytroubleshooter-iam/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.5](https://github.com/googleapis/google-cloud-python/compare/google-cloud-policytroubleshooter-iam-v0.1.4...google-cloud-policytroubleshooter-iam-v0.1.5) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [0.1.4](https://github.com/googleapis/google-cloud-python/compare/google-cloud-policytroubleshooter-iam-v0.1.3...google-cloud-policytroubleshooter-iam-v0.1.4) (2024-02-22) diff --git a/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam/gapic_version.py b/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam/gapic_version.py index 286ce4ad5531..ae12f4dfd596 100644 --- a/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam/gapic_version.py +++ b/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.1.5" # {x-release-please-version} diff --git a/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/gapic_version.py b/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/gapic_version.py index 286ce4ad5531..ae12f4dfd596 100644 --- a/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/gapic_version.py +++ b/packages/google-cloud-policytroubleshooter-iam/google/cloud/policytroubleshooter_iam_v3/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.1.5" # {x-release-please-version} diff --git a/packages/google-cloud-policytroubleshooter-iam/samples/generated_samples/snippet_metadata_google.cloud.policytroubleshooter.iam.v3.json b/packages/google-cloud-policytroubleshooter-iam/samples/generated_samples/snippet_metadata_google.cloud.policytroubleshooter.iam.v3.json index f535fcc64199..5a53273f595a 100644 --- a/packages/google-cloud-policytroubleshooter-iam/samples/generated_samples/snippet_metadata_google.cloud.policytroubleshooter.iam.v3.json +++ b/packages/google-cloud-policytroubleshooter-iam/samples/generated_samples/snippet_metadata_google.cloud.policytroubleshooter.iam.v3.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-policytroubleshooter-iam", - "version": "0.1.4" + "version": "0.1.5" }, "snippets": [ { diff --git a/packages/google-cloud-policytroubleshooter-iam/setup.py b/packages/google-cloud-policytroubleshooter-iam/setup.py index a876c5e69618..97619f888c12 100644 --- a/packages/google-cloud-policytroubleshooter-iam/setup.py +++ b/packages/google-cloud-policytroubleshooter-iam/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-private-ca/CHANGELOG.md b/packages/google-cloud-private-ca/CHANGELOG.md index 23fef92afcb8..80aee7836979 100644 --- a/packages/google-cloud-private-ca/CHANGELOG.md +++ b/packages/google-cloud-private-ca/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.10.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-private-ca-v1.10.2...google-cloud-private-ca-v1.10.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [1.10.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-private-ca-v1.10.1...google-cloud-private-ca-v1.10.2) (2024-02-22) diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca/gapic_version.py b/packages/google-cloud-private-ca/google/cloud/security/privateca/gapic_version.py index 7a033a50e6cd..d74c07c1961e 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca/gapic_version.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.2" # {x-release-please-version} +__version__ = "1.10.3" # {x-release-please-version} diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/gapic_version.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/gapic_version.py index 7a033a50e6cd..d74c07c1961e 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1/gapic_version.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_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.2" # {x-release-please-version} +__version__ = "1.10.3" # {x-release-please-version} diff --git a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/gapic_version.py b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/gapic_version.py index 7a033a50e6cd..d74c07c1961e 100644 --- a/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/gapic_version.py +++ b/packages/google-cloud-private-ca/google/cloud/security/privateca_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.2" # {x-release-please-version} +__version__ = "1.10.3" # {x-release-please-version} diff --git a/packages/google-cloud-private-ca/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1.json b/packages/google-cloud-private-ca/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1.json index 029d47be6cda..667c12ac2b03 100644 --- a/packages/google-cloud-private-ca/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1.json +++ b/packages/google-cloud-private-ca/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-private-ca", - "version": "1.10.2" + "version": "1.10.3" }, "snippets": [ { diff --git a/packages/google-cloud-private-ca/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1beta1.json b/packages/google-cloud-private-ca/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1beta1.json index 3b6c852e968e..9f17adda75ee 100644 --- a/packages/google-cloud-private-ca/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1beta1.json +++ b/packages/google-cloud-private-ca/samples/generated_samples/snippet_metadata_google.cloud.security.privateca.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-private-ca", - "version": "1.10.2" + "version": "1.10.3" }, "snippets": [ { diff --git a/packages/google-cloud-private-ca/setup.py b/packages/google-cloud-private-ca/setup.py index 360293dc8696..679a448ba8fb 100644 --- a/packages/google-cloud-private-ca/setup.py +++ b/packages/google-cloud-private-ca/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-private-catalog/CHANGELOG.md b/packages/google-cloud-private-catalog/CHANGELOG.md index 06cb758855bf..696c19a76990 100644 --- a/packages/google-cloud-private-catalog/CHANGELOG.md +++ b/packages/google-cloud-private-catalog/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.9.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-private-catalog-v0.9.8...google-cloud-private-catalog-v0.9.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [0.9.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-private-catalog-v0.9.7...google-cloud-private-catalog-v0.9.8) (2024-02-22) diff --git a/packages/google-cloud-private-catalog/google/cloud/privatecatalog/gapic_version.py b/packages/google-cloud-private-catalog/google/cloud/privatecatalog/gapic_version.py index 766951197b66..301bd68cc9f0 100644 --- a/packages/google-cloud-private-catalog/google/cloud/privatecatalog/gapic_version.py +++ b/packages/google-cloud-private-catalog/google/cloud/privatecatalog/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.9.8" # {x-release-please-version} +__version__ = "0.9.9" # {x-release-please-version} diff --git a/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/gapic_version.py b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/gapic_version.py index 766951197b66..301bd68cc9f0 100644 --- a/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/gapic_version.py +++ b/packages/google-cloud-private-catalog/google/cloud/privatecatalog_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.9.8" # {x-release-please-version} +__version__ = "0.9.9" # {x-release-please-version} diff --git a/packages/google-cloud-private-catalog/samples/generated_samples/snippet_metadata_google.cloud.privatecatalog.v1beta1.json b/packages/google-cloud-private-catalog/samples/generated_samples/snippet_metadata_google.cloud.privatecatalog.v1beta1.json index 29696ad777a5..71e29a1e06d2 100644 --- a/packages/google-cloud-private-catalog/samples/generated_samples/snippet_metadata_google.cloud.privatecatalog.v1beta1.json +++ b/packages/google-cloud-private-catalog/samples/generated_samples/snippet_metadata_google.cloud.privatecatalog.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-private-catalog", - "version": "0.9.8" + "version": "0.9.9" }, "snippets": [ { diff --git a/packages/google-cloud-private-catalog/setup.py b/packages/google-cloud-private-catalog/setup.py index 14405e53e827..8f17452e47f8 100644 --- a/packages/google-cloud-private-catalog/setup.py +++ b/packages/google-cloud-private-catalog/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-public-ca/CHANGELOG.md b/packages/google-cloud-public-ca/CHANGELOG.md index bb5bcab81405..11fcfc500035 100644 --- a/packages/google-cloud-public-ca/CHANGELOG.md +++ b/packages/google-cloud-public-ca/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.3.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-public-ca-v0.3.8...google-cloud-public-ca-v0.3.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [0.3.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-public-ca-v0.3.7...google-cloud-public-ca-v0.3.8) (2024-02-22) diff --git a/packages/google-cloud-public-ca/google/cloud/security/publicca/gapic_version.py b/packages/google-cloud-public-ca/google/cloud/security/publicca/gapic_version.py index 9c72996dc3e9..807d78fcb4c5 100644 --- a/packages/google-cloud-public-ca/google/cloud/security/publicca/gapic_version.py +++ b/packages/google-cloud-public-ca/google/cloud/security/publicca/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.8" # {x-release-please-version} +__version__ = "0.3.9" # {x-release-please-version} diff --git a/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/gapic_version.py b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/gapic_version.py index 9c72996dc3e9..807d78fcb4c5 100644 --- a/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/gapic_version.py +++ b/packages/google-cloud-public-ca/google/cloud/security/publicca_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.8" # {x-release-please-version} +__version__ = "0.3.9" # {x-release-please-version} diff --git a/packages/google-cloud-public-ca/samples/generated_samples/snippet_metadata_google.cloud.security.publicca.v1beta1.json b/packages/google-cloud-public-ca/samples/generated_samples/snippet_metadata_google.cloud.security.publicca.v1beta1.json index 0cb636dc4a50..42f6bbf9073a 100644 --- a/packages/google-cloud-public-ca/samples/generated_samples/snippet_metadata_google.cloud.security.publicca.v1beta1.json +++ b/packages/google-cloud-public-ca/samples/generated_samples/snippet_metadata_google.cloud.security.publicca.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-public-ca", - "version": "0.3.8" + "version": "0.3.9" }, "snippets": [ { diff --git a/packages/google-cloud-public-ca/setup.py b/packages/google-cloud-public-ca/setup.py index c68b4137c566..a01299de5976 100644 --- a/packages/google-cloud-public-ca/setup.py +++ b/packages/google-cloud-public-ca/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-rapidmigrationassessment/CHANGELOG.md b/packages/google-cloud-rapidmigrationassessment/CHANGELOG.md index 69baa8ebf878..102284ba2797 100644 --- a/packages/google-cloud-rapidmigrationassessment/CHANGELOG.md +++ b/packages/google-cloud-rapidmigrationassessment/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-rapidmigrationassessment-v0.1.6...google-cloud-rapidmigrationassessment-v0.1.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [0.1.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-rapidmigrationassessment-v0.1.5...google-cloud-rapidmigrationassessment-v0.1.6) (2024-02-22) diff --git a/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment/gapic_version.py b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment/gapic_version.py index 60402a4567d1..e34e491c76d0 100644 --- a/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment/gapic_version.py +++ b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.6" # {x-release-please-version} +__version__ = "0.1.7" # {x-release-please-version} diff --git a/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/gapic_version.py b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/gapic_version.py index 60402a4567d1..e34e491c76d0 100644 --- a/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_v1/gapic_version.py +++ b/packages/google-cloud-rapidmigrationassessment/google/cloud/rapidmigrationassessment_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.6" # {x-release-please-version} +__version__ = "0.1.7" # {x-release-please-version} diff --git a/packages/google-cloud-rapidmigrationassessment/samples/generated_samples/snippet_metadata_google.cloud.rapidmigrationassessment.v1.json b/packages/google-cloud-rapidmigrationassessment/samples/generated_samples/snippet_metadata_google.cloud.rapidmigrationassessment.v1.json index 0f599ad12d34..10d580e217ed 100644 --- a/packages/google-cloud-rapidmigrationassessment/samples/generated_samples/snippet_metadata_google.cloud.rapidmigrationassessment.v1.json +++ b/packages/google-cloud-rapidmigrationassessment/samples/generated_samples/snippet_metadata_google.cloud.rapidmigrationassessment.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-rapidmigrationassessment", - "version": "0.1.6" + "version": "0.1.7" }, "snippets": [ { diff --git a/packages/google-cloud-rapidmigrationassessment/setup.py b/packages/google-cloud-rapidmigrationassessment/setup.py index 83d64a179e89..aea8aa838bf7 100644 --- a/packages/google-cloud-rapidmigrationassessment/setup.py +++ b/packages/google-cloud-rapidmigrationassessment/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-recaptcha-enterprise/CHANGELOG.md b/packages/google-cloud-recaptcha-enterprise/CHANGELOG.md index c8ee500d4548..7cc067980c49 100644 --- a/packages/google-cloud-recaptcha-enterprise/CHANGELOG.md +++ b/packages/google-cloud-recaptcha-enterprise/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.18.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-recaptcha-enterprise-v1.18.0...google-cloud-recaptcha-enterprise-v1.18.1) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [1.18.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-recaptcha-enterprise-v1.17.1...google-cloud-recaptcha-enterprise-v1.18.0) (2024-02-22) 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 1d1b45f2c68a..64e0dc747823 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.18.0" # {x-release-please-version} +__version__ = "1.18.1" # {x-release-please-version} 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 1d1b45f2c68a..64e0dc747823 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.18.0" # {x-release-please-version} +__version__ = "1.18.1" # {x-release-please-version} 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 9d96c9fcab89..72b0cf4146d5 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.18.0" + "version": "1.18.1" }, "snippets": [ { diff --git a/packages/google-cloud-recaptcha-enterprise/setup.py b/packages/google-cloud-recaptcha-enterprise/setup.py index ddfa17a14bfb..848861183927 100644 --- a/packages/google-cloud-recaptcha-enterprise/setup.py +++ b/packages/google-cloud-recaptcha-enterprise/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-recommendations-ai/CHANGELOG.md b/packages/google-cloud-recommendations-ai/CHANGELOG.md index 63bc68e129f2..47bbea8accff 100644 --- a/packages/google-cloud-recommendations-ai/CHANGELOG.md +++ b/packages/google-cloud-recommendations-ai/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.10.10](https://github.com/googleapis/google-cloud-python/compare/google-cloud-recommendations-ai-v0.10.9...google-cloud-recommendations-ai-v0.10.10) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [0.10.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-recommendations-ai-v0.10.8...google-cloud-recommendations-ai-v0.10.9) (2024-02-22) diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine/gapic_version.py b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine/gapic_version.py index 4d3143c8cc8e..e3f784024799 100644 --- a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine/gapic_version.py +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.10.9" # {x-release-please-version} +__version__ = "0.10.10" # {x-release-please-version} diff --git a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/gapic_version.py b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/gapic_version.py index 4d3143c8cc8e..e3f784024799 100644 --- a/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/gapic_version.py +++ b/packages/google-cloud-recommendations-ai/google/cloud/recommendationengine_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.10.9" # {x-release-please-version} +__version__ = "0.10.10" # {x-release-please-version} diff --git a/packages/google-cloud-recommendations-ai/samples/generated_samples/snippet_metadata_google.cloud.recommendationengine.v1beta1.json b/packages/google-cloud-recommendations-ai/samples/generated_samples/snippet_metadata_google.cloud.recommendationengine.v1beta1.json index b20b2d3482aa..ade8f6b2488b 100644 --- a/packages/google-cloud-recommendations-ai/samples/generated_samples/snippet_metadata_google.cloud.recommendationengine.v1beta1.json +++ b/packages/google-cloud-recommendations-ai/samples/generated_samples/snippet_metadata_google.cloud.recommendationengine.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-recommendations-ai", - "version": "0.10.9" + "version": "0.10.10" }, "snippets": [ { diff --git a/packages/google-cloud-recommendations-ai/setup.py b/packages/google-cloud-recommendations-ai/setup.py index 0cb541cde769..625b59d5f6ad 100644 --- a/packages/google-cloud-recommendations-ai/setup.py +++ b/packages/google-cloud-recommendations-ai/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-recommender/CHANGELOG.md b/packages/google-cloud-recommender/CHANGELOG.md index 42c5bb7c5e13..7cbf255a5565 100644 --- a/packages/google-cloud-recommender/CHANGELOG.md +++ b/packages/google-cloud-recommender/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-recommender/#history +## [2.15.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-recommender-v2.15.2...google-cloud-recommender-v2.15.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [2.15.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-recommender-v2.15.1...google-cloud-recommender-v2.15.2) (2024-02-22) diff --git a/packages/google-cloud-recommender/google/cloud/recommender/gapic_version.py b/packages/google-cloud-recommender/google/cloud/recommender/gapic_version.py index 0c0ea09abc84..5930a4f7e8d2 100644 --- a/packages/google-cloud-recommender/google/cloud/recommender/gapic_version.py +++ b/packages/google-cloud-recommender/google/cloud/recommender/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.15.2" # {x-release-please-version} +__version__ = "2.15.3" # {x-release-please-version} diff --git a/packages/google-cloud-recommender/google/cloud/recommender_v1/gapic_version.py b/packages/google-cloud-recommender/google/cloud/recommender_v1/gapic_version.py index 0c0ea09abc84..5930a4f7e8d2 100644 --- a/packages/google-cloud-recommender/google/cloud/recommender_v1/gapic_version.py +++ b/packages/google-cloud-recommender/google/cloud/recommender_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.15.2" # {x-release-please-version} +__version__ = "2.15.3" # {x-release-please-version} diff --git a/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/gapic_version.py b/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/gapic_version.py index 0c0ea09abc84..5930a4f7e8d2 100644 --- a/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/gapic_version.py +++ b/packages/google-cloud-recommender/google/cloud/recommender_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.15.2" # {x-release-please-version} +__version__ = "2.15.3" # {x-release-please-version} diff --git a/packages/google-cloud-recommender/samples/generated_samples/snippet_metadata_google.cloud.recommender.v1.json b/packages/google-cloud-recommender/samples/generated_samples/snippet_metadata_google.cloud.recommender.v1.json index bae457d8ea0c..5d40b794b34b 100644 --- a/packages/google-cloud-recommender/samples/generated_samples/snippet_metadata_google.cloud.recommender.v1.json +++ b/packages/google-cloud-recommender/samples/generated_samples/snippet_metadata_google.cloud.recommender.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-recommender", - "version": "2.15.2" + "version": "2.15.3" }, "snippets": [ { diff --git a/packages/google-cloud-recommender/samples/generated_samples/snippet_metadata_google.cloud.recommender.v1beta1.json b/packages/google-cloud-recommender/samples/generated_samples/snippet_metadata_google.cloud.recommender.v1beta1.json index 099fe0497217..a0d936b1ecfe 100644 --- a/packages/google-cloud-recommender/samples/generated_samples/snippet_metadata_google.cloud.recommender.v1beta1.json +++ b/packages/google-cloud-recommender/samples/generated_samples/snippet_metadata_google.cloud.recommender.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-recommender", - "version": "2.15.2" + "version": "2.15.3" }, "snippets": [ { diff --git a/packages/google-cloud-recommender/setup.py b/packages/google-cloud-recommender/setup.py index 920ee8639928..8c8b21449111 100644 --- a/packages/google-cloud-recommender/setup.py +++ b/packages/google-cloud-recommender/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-redis-cluster/CHANGELOG.md b/packages/google-cloud-redis-cluster/CHANGELOG.md index 32892c9f403c..f508072b1048 100644 --- a/packages/google-cloud-redis-cluster/CHANGELOG.md +++ b/packages/google-cloud-redis-cluster/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.5](https://github.com/googleapis/google-cloud-python/compare/google-cloud-redis-cluster-v0.1.4...google-cloud-redis-cluster-v0.1.5) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12386](https://github.com/googleapis/google-cloud-python/issues/12386)) ([edcad16](https://github.com/googleapis/google-cloud-python/commit/edcad1661973ae1677c69b3fc1c03c3069ec0e71)) + ## [0.1.4](https://github.com/googleapis/google-cloud-python/compare/google-cloud-redis-cluster-v0.1.3...google-cloud-redis-cluster-v0.1.4) (2024-02-22) diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster/gapic_version.py b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster/gapic_version.py index 286ce4ad5531..ae12f4dfd596 100644 --- a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster/gapic_version.py +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.1.5" # {x-release-please-version} diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/gapic_version.py b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/gapic_version.py index 286ce4ad5531..ae12f4dfd596 100644 --- a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1/gapic_version.py +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_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.4" # {x-release-please-version} +__version__ = "0.1.5" # {x-release-please-version} diff --git a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/gapic_version.py b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/gapic_version.py index 286ce4ad5531..ae12f4dfd596 100644 --- a/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/gapic_version.py +++ b/packages/google-cloud-redis-cluster/google/cloud/redis_cluster_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.1.5" # {x-release-please-version} diff --git a/packages/google-cloud-redis-cluster/samples/generated_samples/snippet_metadata_google.cloud.redis.cluster.v1.json b/packages/google-cloud-redis-cluster/samples/generated_samples/snippet_metadata_google.cloud.redis.cluster.v1.json index 6baa19070820..0e73ed6e524d 100644 --- a/packages/google-cloud-redis-cluster/samples/generated_samples/snippet_metadata_google.cloud.redis.cluster.v1.json +++ b/packages/google-cloud-redis-cluster/samples/generated_samples/snippet_metadata_google.cloud.redis.cluster.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-redis-cluster", - "version": "0.1.4" + "version": "0.1.5" }, "snippets": [ { diff --git a/packages/google-cloud-redis-cluster/samples/generated_samples/snippet_metadata_google.cloud.redis.cluster.v1beta1.json b/packages/google-cloud-redis-cluster/samples/generated_samples/snippet_metadata_google.cloud.redis.cluster.v1beta1.json index 40cad6dbfe20..98630b069d02 100644 --- a/packages/google-cloud-redis-cluster/samples/generated_samples/snippet_metadata_google.cloud.redis.cluster.v1beta1.json +++ b/packages/google-cloud-redis-cluster/samples/generated_samples/snippet_metadata_google.cloud.redis.cluster.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-redis-cluster", - "version": "0.1.4" + "version": "0.1.5" }, "snippets": [ { diff --git a/packages/google-cloud-redis-cluster/setup.py b/packages/google-cloud-redis-cluster/setup.py index 997971a52f92..f481bec231a0 100644 --- a/packages/google-cloud-redis-cluster/setup.py +++ b/packages/google-cloud-redis-cluster/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-redis/CHANGELOG.md b/packages/google-cloud-redis/CHANGELOG.md index f6d5073496f6..cb34af8dd74d 100644 --- a/packages/google-cloud-redis/CHANGELOG.md +++ b/packages/google-cloud-redis/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-redis/#history +## [2.15.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-redis-v2.15.2...google-cloud-redis-v2.15.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [2.15.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-redis-v2.15.1...google-cloud-redis-v2.15.2) (2024-02-22) diff --git a/packages/google-cloud-redis/google/cloud/redis/gapic_version.py b/packages/google-cloud-redis/google/cloud/redis/gapic_version.py index 0c0ea09abc84..5930a4f7e8d2 100644 --- a/packages/google-cloud-redis/google/cloud/redis/gapic_version.py +++ b/packages/google-cloud-redis/google/cloud/redis/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.15.2" # {x-release-please-version} +__version__ = "2.15.3" # {x-release-please-version} diff --git a/packages/google-cloud-redis/google/cloud/redis_v1/gapic_version.py b/packages/google-cloud-redis/google/cloud/redis_v1/gapic_version.py index 0c0ea09abc84..5930a4f7e8d2 100644 --- a/packages/google-cloud-redis/google/cloud/redis_v1/gapic_version.py +++ b/packages/google-cloud-redis/google/cloud/redis_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.15.2" # {x-release-please-version} +__version__ = "2.15.3" # {x-release-please-version} diff --git a/packages/google-cloud-redis/google/cloud/redis_v1beta1/gapic_version.py b/packages/google-cloud-redis/google/cloud/redis_v1beta1/gapic_version.py index 0c0ea09abc84..5930a4f7e8d2 100644 --- a/packages/google-cloud-redis/google/cloud/redis_v1beta1/gapic_version.py +++ b/packages/google-cloud-redis/google/cloud/redis_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.15.2" # {x-release-please-version} +__version__ = "2.15.3" # {x-release-please-version} diff --git a/packages/google-cloud-redis/samples/generated_samples/snippet_metadata_google.cloud.redis.v1.json b/packages/google-cloud-redis/samples/generated_samples/snippet_metadata_google.cloud.redis.v1.json index 46389777d5a3..32884467b2f1 100644 --- a/packages/google-cloud-redis/samples/generated_samples/snippet_metadata_google.cloud.redis.v1.json +++ b/packages/google-cloud-redis/samples/generated_samples/snippet_metadata_google.cloud.redis.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-redis", - "version": "2.15.2" + "version": "2.15.3" }, "snippets": [ { diff --git a/packages/google-cloud-redis/samples/generated_samples/snippet_metadata_google.cloud.redis.v1beta1.json b/packages/google-cloud-redis/samples/generated_samples/snippet_metadata_google.cloud.redis.v1beta1.json index b905500951c0..e058b54ae8b8 100644 --- a/packages/google-cloud-redis/samples/generated_samples/snippet_metadata_google.cloud.redis.v1beta1.json +++ b/packages/google-cloud-redis/samples/generated_samples/snippet_metadata_google.cloud.redis.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-redis", - "version": "2.15.2" + "version": "2.15.3" }, "snippets": [ { diff --git a/packages/google-cloud-redis/setup.py b/packages/google-cloud-redis/setup.py index 5878b242d069..b32d9dd3db87 100644 --- a/packages/google-cloud-redis/setup.py +++ b/packages/google-cloud-redis/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-resource-manager/CHANGELOG.md b/packages/google-cloud-resource-manager/CHANGELOG.md index 16c9d16ac1af..a60f876b70b7 100644 --- a/packages/google-cloud-resource-manager/CHANGELOG.md +++ b/packages/google-cloud-resource-manager/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-resource-manager/#history +## [1.12.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-resource-manager-v1.12.2...google-cloud-resource-manager-v1.12.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [1.12.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-resource-manager-v1.12.1...google-cloud-resource-manager-v1.12.2) (2024-02-22) diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager/gapic_version.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager/gapic_version.py index 394a70bae1a3..12049b60eb6c 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager/gapic_version.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.12.2" # {x-release-please-version} +__version__ = "1.12.3" # {x-release-please-version} diff --git a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/gapic_version.py b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/gapic_version.py index 394a70bae1a3..12049b60eb6c 100644 --- a/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/gapic_version.py +++ b/packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.12.2" # {x-release-please-version} +__version__ = "1.12.3" # {x-release-please-version} diff --git a/packages/google-cloud-resource-manager/samples/generated_samples/snippet_metadata_google.cloud.resourcemanager.v3.json b/packages/google-cloud-resource-manager/samples/generated_samples/snippet_metadata_google.cloud.resourcemanager.v3.json index b09e31696a84..d4d8bc60d68a 100644 --- a/packages/google-cloud-resource-manager/samples/generated_samples/snippet_metadata_google.cloud.resourcemanager.v3.json +++ b/packages/google-cloud-resource-manager/samples/generated_samples/snippet_metadata_google.cloud.resourcemanager.v3.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-resource-manager", - "version": "1.12.2" + "version": "1.12.3" }, "snippets": [ { diff --git a/packages/google-cloud-resource-manager/setup.py b/packages/google-cloud-resource-manager/setup.py index 0ba070b012b4..a5c724648656 100644 --- a/packages/google-cloud-resource-manager/setup.py +++ b/packages/google-cloud-resource-manager/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-resource-settings/CHANGELOG.md b/packages/google-cloud-resource-settings/CHANGELOG.md index 4475391cb773..cea659fa64a8 100644 --- a/packages/google-cloud-resource-settings/CHANGELOG.md +++ b/packages/google-cloud-resource-settings/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.9.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-resource-settings-v1.9.2...google-cloud-resource-settings-v1.9.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [1.9.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-resource-settings-v1.9.1...google-cloud-resource-settings-v1.9.2) (2024-02-22) diff --git a/packages/google-cloud-resource-settings/google/cloud/resourcesettings/gapic_version.py b/packages/google-cloud-resource-settings/google/cloud/resourcesettings/gapic_version.py index f14078b6f555..ec42a8e289c4 100644 --- a/packages/google-cloud-resource-settings/google/cloud/resourcesettings/gapic_version.py +++ b/packages/google-cloud-resource-settings/google/cloud/resourcesettings/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} diff --git a/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/gapic_version.py b/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/gapic_version.py index f14078b6f555..ec42a8e289c4 100644 --- a/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/gapic_version.py +++ b/packages/google-cloud-resource-settings/google/cloud/resourcesettings_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} diff --git a/packages/google-cloud-resource-settings/samples/generated_samples/snippet_metadata_google.cloud.resourcesettings.v1.json b/packages/google-cloud-resource-settings/samples/generated_samples/snippet_metadata_google.cloud.resourcesettings.v1.json index e6cf7aee5545..0837384d9a97 100644 --- a/packages/google-cloud-resource-settings/samples/generated_samples/snippet_metadata_google.cloud.resourcesettings.v1.json +++ b/packages/google-cloud-resource-settings/samples/generated_samples/snippet_metadata_google.cloud.resourcesettings.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-resource-settings", - "version": "1.9.2" + "version": "1.9.3" }, "snippets": [ { diff --git a/packages/google-cloud-resource-settings/setup.py b/packages/google-cloud-resource-settings/setup.py index 672c098fad48..5ea265515e56 100644 --- a/packages/google-cloud-resource-settings/setup.py +++ b/packages/google-cloud-resource-settings/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-retail/CHANGELOG.md b/packages/google-cloud-retail/CHANGELOG.md index 788d8f3cb187..8be9bec95433 100644 --- a/packages/google-cloud-retail/CHANGELOG.md +++ b/packages/google-cloud-retail/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.20.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-retail-v1.20.0...google-cloud-retail-v1.20.1) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [1.20.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-retail-v1.19.1...google-cloud-retail-v1.20.0) (2024-02-22) diff --git a/packages/google-cloud-retail/google/cloud/retail/gapic_version.py b/packages/google-cloud-retail/google/cloud/retail/gapic_version.py index 41d9773e4f1f..2b739d3ea276 100644 --- a/packages/google-cloud-retail/google/cloud/retail/gapic_version.py +++ b/packages/google-cloud-retail/google/cloud/retail/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-retail/google/cloud/retail_v2/gapic_version.py b/packages/google-cloud-retail/google/cloud/retail_v2/gapic_version.py index 41d9773e4f1f..2b739d3ea276 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2/gapic_version.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2/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-retail/google/cloud/retail_v2alpha/gapic_version.py b/packages/google-cloud-retail/google/cloud/retail_v2alpha/gapic_version.py index 41d9773e4f1f..2b739d3ea276 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2alpha/gapic_version.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2alpha/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-retail/google/cloud/retail_v2beta/gapic_version.py b/packages/google-cloud-retail/google/cloud/retail_v2beta/gapic_version.py index 41d9773e4f1f..2b739d3ea276 100644 --- a/packages/google-cloud-retail/google/cloud/retail_v2beta/gapic_version.py +++ b/packages/google-cloud-retail/google/cloud/retail_v2beta/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-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2.json b/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2.json index 56e21ef86554..39bd4549c096 100644 --- a/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2.json +++ b/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-retail", - "version": "1.20.0" + "version": "1.20.1" }, "snippets": [ { diff --git a/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2alpha.json b/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2alpha.json index 49f131b9b451..45bf6cf2f15b 100644 --- a/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2alpha.json +++ b/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-retail", - "version": "1.20.0" + "version": "1.20.1" }, "snippets": [ { diff --git a/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2beta.json b/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2beta.json index 565a4603d961..eb0020d2e055 100644 --- a/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2beta.json +++ b/packages/google-cloud-retail/samples/generated_samples/snippet_metadata_google.cloud.retail.v2beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-retail", - "version": "1.20.0" + "version": "1.20.1" }, "snippets": [ { diff --git a/packages/google-cloud-retail/setup.py b/packages/google-cloud-retail/setup.py index 5a652c10a897..32bac2e964fa 100644 --- a/packages/google-cloud-retail/setup.py +++ b/packages/google-cloud-retail/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-run/CHANGELOG.md b/packages/google-cloud-run/CHANGELOG.md index def239795e10..12e6908c9f6a 100644 --- a/packages/google-cloud-run/CHANGELOG.md +++ b/packages/google-cloud-run/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## [0.10.5](https://github.com/googleapis/google-cloud-python/compare/google-cloud-run-v0.10.4...google-cloud-run-v0.10.5) (2024-03-05) + + +### Features + +* Allow disabling the default URL (run.app) for Cloud Run Services ([5535d1e](https://github.com/googleapis/google-cloud-python/commit/5535d1e6288f790899f7f6b5091ad113621da176)) +* Support disabling waiting for health checks during Service deployment. ([5535d1e](https://github.com/googleapis/google-cloud-python/commit/5535d1e6288f790899f7f6b5091ad113621da176)) +* Support mounting NFS and GCS volumes in Cloud Run Jobs and Services ([5535d1e](https://github.com/googleapis/google-cloud-python/commit/5535d1e6288f790899f7f6b5091ad113621da176)) +* Support specifying a per-Service min-instance-count ([5535d1e](https://github.com/googleapis/google-cloud-python/commit/5535d1e6288f790899f7f6b5091ad113621da176)) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + + +### Documentation + +* Clarify some defaults and required or optional values ([5535d1e](https://github.com/googleapis/google-cloud-python/commit/5535d1e6288f790899f7f6b5091ad113621da176)) + ## [0.10.4](https://github.com/googleapis/google-cloud-python/compare/google-cloud-run-v0.10.3...google-cloud-run-v0.10.4) (2024-02-22) diff --git a/packages/google-cloud-run/google/cloud/run/__init__.py b/packages/google-cloud-run/google/cloud/run/__init__.py index 6d215f9bcb2b..6115eaf58d37 100644 --- a/packages/google-cloud-run/google/cloud/run/__init__.py +++ b/packages/google-cloud-run/google/cloud/run/__init__.py @@ -56,9 +56,11 @@ EmptyDirVolumeSource, EnvVar, EnvVarSource, + GCSVolumeSource, GRPCAction, HTTPGetAction, HTTPHeader, + NFSVolumeSource, Probe, ResourceRequirements, SecretKeySelector, @@ -85,6 +87,7 @@ Service, UpdateServiceRequest, ) +from google.cloud.run_v2.types.status import RevisionScalingStatus from google.cloud.run_v2.types.task import ( GetTaskRequest, ListTasksRequest, @@ -104,6 +107,7 @@ ExecutionEnvironment, IngressTraffic, RevisionScaling, + ServiceScaling, VpcAccess, ) @@ -141,9 +145,11 @@ "EmptyDirVolumeSource", "EnvVar", "EnvVarSource", + "GCSVolumeSource", "GRPCAction", "HTTPGetAction", "HTTPHeader", + "NFSVolumeSource", "Probe", "ResourceRequirements", "SecretKeySelector", @@ -165,6 +171,7 @@ "ListServicesResponse", "Service", "UpdateServiceRequest", + "RevisionScalingStatus", "GetTaskRequest", "ListTasksRequest", "ListTasksResponse", @@ -176,6 +183,7 @@ "TrafficTargetAllocationType", "BinaryAuthorization", "RevisionScaling", + "ServiceScaling", "VpcAccess", "EncryptionKeyRevocationAction", "ExecutionEnvironment", diff --git a/packages/google-cloud-run/google/cloud/run/gapic_version.py b/packages/google-cloud-run/google/cloud/run/gapic_version.py index 0bfda03894ef..6416b8967cc6 100644 --- a/packages/google-cloud-run/google/cloud/run/gapic_version.py +++ b/packages/google-cloud-run/google/cloud/run/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.10.4" # {x-release-please-version} +__version__ = "0.10.5" # {x-release-please-version} diff --git a/packages/google-cloud-run/google/cloud/run_v2/__init__.py b/packages/google-cloud-run/google/cloud/run_v2/__init__.py index 11fd2d75146c..54f45f7d7b4b 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/__init__.py +++ b/packages/google-cloud-run/google/cloud/run_v2/__init__.py @@ -51,9 +51,11 @@ EmptyDirVolumeSource, EnvVar, EnvVarSource, + GCSVolumeSource, GRPCAction, HTTPGetAction, HTTPHeader, + NFSVolumeSource, Probe, ResourceRequirements, SecretKeySelector, @@ -80,6 +82,7 @@ Service, UpdateServiceRequest, ) +from .types.status import RevisionScalingStatus from .types.task import ( GetTaskRequest, ListTasksRequest, @@ -99,6 +102,7 @@ ExecutionEnvironment, IngressTraffic, RevisionScaling, + ServiceScaling, VpcAccess, ) @@ -129,6 +133,7 @@ "ExecutionReference", "ExecutionTemplate", "ExecutionsClient", + "GCSVolumeSource", "GRPCAction", "GetExecutionRequest", "GetJobRequest", @@ -150,16 +155,19 @@ "ListServicesResponse", "ListTasksRequest", "ListTasksResponse", + "NFSVolumeSource", "Probe", "ResourceRequirements", "Revision", "RevisionScaling", + "RevisionScalingStatus", "RevisionTemplate", "RevisionsClient", "RunJobRequest", "SecretKeySelector", "SecretVolumeSource", "Service", + "ServiceScaling", "ServicesClient", "TCPSocketAction", "Task", diff --git a/packages/google-cloud-run/google/cloud/run_v2/gapic_version.py b/packages/google-cloud-run/google/cloud/run_v2/gapic_version.py index 0bfda03894ef..6416b8967cc6 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/gapic_version.py +++ b/packages/google-cloud-run/google/cloud/run_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.10.4" # {x-release-please-version} +__version__ = "0.10.5" # {x-release-please-version} diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/async_client.py b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/async_client.py index 0365b769dc93..a19520443b18 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/async_client.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/async_client.py @@ -51,7 +51,13 @@ from google.protobuf import timestamp_pb2 # type: ignore from google.cloud.run_v2.services.revisions import pagers -from google.cloud.run_v2.types import condition, k8s_min, revision, vendor_settings +from google.cloud.run_v2.types import ( + condition, + k8s_min, + revision, + status, + vendor_settings, +) from .client import RevisionsClient from .transports.base import DEFAULT_CLIENT_INFO, RevisionsTransport diff --git a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/client.py b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/client.py index 37cd9c973513..174fb5ab4f56 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/services/revisions/client.py +++ b/packages/google-cloud-run/google/cloud/run_v2/services/revisions/client.py @@ -56,7 +56,13 @@ from google.protobuf import timestamp_pb2 # type: ignore from google.cloud.run_v2.services.revisions import pagers -from google.cloud.run_v2.types import condition, k8s_min, revision, vendor_settings +from google.cloud.run_v2.types import ( + condition, + k8s_min, + revision, + status, + vendor_settings, +) from .transports.base import DEFAULT_CLIENT_INFO, RevisionsTransport from .transports.grpc import RevisionsGrpcTransport diff --git a/packages/google-cloud-run/google/cloud/run_v2/types/__init__.py b/packages/google-cloud-run/google/cloud/run_v2/types/__init__.py index 3603276380bc..757558f0b2da 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/types/__init__.py +++ b/packages/google-cloud-run/google/cloud/run_v2/types/__init__.py @@ -41,9 +41,11 @@ EmptyDirVolumeSource, EnvVar, EnvVarSource, + GCSVolumeSource, GRPCAction, HTTPGetAction, HTTPHeader, + NFSVolumeSource, Probe, ResourceRequirements, SecretKeySelector, @@ -70,6 +72,7 @@ Service, UpdateServiceRequest, ) +from .status import RevisionScalingStatus from .task import ( GetTaskRequest, ListTasksRequest, @@ -89,6 +92,7 @@ ExecutionEnvironment, IngressTraffic, RevisionScaling, + ServiceScaling, VpcAccess, ) @@ -116,9 +120,11 @@ "EmptyDirVolumeSource", "EnvVar", "EnvVarSource", + "GCSVolumeSource", "GRPCAction", "HTTPGetAction", "HTTPHeader", + "NFSVolumeSource", "Probe", "ResourceRequirements", "SecretKeySelector", @@ -140,6 +146,7 @@ "ListServicesResponse", "Service", "UpdateServiceRequest", + "RevisionScalingStatus", "GetTaskRequest", "ListTasksRequest", "ListTasksResponse", @@ -151,6 +158,7 @@ "TrafficTargetAllocationType", "BinaryAuthorization", "RevisionScaling", + "ServiceScaling", "VpcAccess", "EncryptionKeyRevocationAction", "ExecutionEnvironment", diff --git a/packages/google-cloud-run/google/cloud/run_v2/types/k8s_min.py b/packages/google-cloud-run/google/cloud/run_v2/types/k8s_min.py index e24e19f82fcb..ad73be4df141 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/types/k8s_min.py +++ b/packages/google-cloud-run/google/cloud/run_v2/types/k8s_min.py @@ -34,6 +34,8 @@ "VersionToPath", "CloudSqlInstance", "EmptyDirVolumeSource", + "NFSVolumeSource", + "GCSVolumeSource", "Probe", "HTTPGetAction", "HTTPHeader", @@ -167,7 +169,7 @@ class ResourceRequirements(proto.Message): Attributes: limits (MutableMapping[str, str]): - Only ´memory´ and 'cpu' are supported. + Only ``memory`` and ``cpu`` keys in the map are supported. .. raw:: html @@ -178,8 +180,11 @@ class ResourceRequirements(proto.Message): * For supported 'memory' values and syntax, go to https://cloud.google.com/run/docs/configuring/memory-limits cpu_idle (bool): - Determines whether CPU should be throttled or - not outside of requests. + Determines whether CPU is only allocated + during requests (true by default). However, if + ResourceRequirements is set, the caller must + explicitly set this field to true to preserve + the default behavior. startup_cpu_boost (bool): Determines whether CPU should be boosted on startup of a new container instance above the @@ -374,6 +379,16 @@ class Volume(proto.Message): empty_dir (google.cloud.run_v2.types.EmptyDirVolumeSource): Ephemeral storage used as a shared volume. + This field is a member of `oneof`_ ``volume_type``. + nfs (google.cloud.run_v2.types.NFSVolumeSource): + For NFS Voumes, contains the path to the nfs + Volume + + This field is a member of `oneof`_ ``volume_type``. + gcs (google.cloud.run_v2.types.GCSVolumeSource): + Persistent storage backed by a Google Cloud + Storage bucket. + This field is a member of `oneof`_ ``volume_type``. """ @@ -399,6 +414,18 @@ class Volume(proto.Message): oneof="volume_type", message="EmptyDirVolumeSource", ) + nfs: "NFSVolumeSource" = proto.Field( + proto.MESSAGE, + number=5, + oneof="volume_type", + message="NFSVolumeSource", + ) + gcs: "GCSVolumeSource" = proto.Field( + proto.MESSAGE, + number=6, + oneof="volume_type", + message="GCSVolumeSource", + ) class SecretVolumeSource(proto.Message): @@ -588,6 +615,52 @@ class Medium(proto.Enum): ) +class NFSVolumeSource(proto.Message): + r"""Represents an NFS mount. + + Attributes: + server (str): + Hostname or IP address of the NFS server + path (str): + Path that is exported by the NFS server. + read_only (bool): + If true, mount the NFS volume as read only + """ + + server: str = proto.Field( + proto.STRING, + number=1, + ) + path: str = proto.Field( + proto.STRING, + number=2, + ) + read_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class GCSVolumeSource(proto.Message): + r"""Represents a GCS Bucket mounted as a volume. + + Attributes: + bucket (str): + GCS Bucket name + read_only (bool): + If true, mount the GCS bucket as read-only + """ + + bucket: str = proto.Field( + proto.STRING, + number=1, + ) + read_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + + class Probe(proto.Message): r"""Probe describes a health check to be performed against a container to determine whether it is alive or ready to receive diff --git a/packages/google-cloud-run/google/cloud/run_v2/types/revision.py b/packages/google-cloud-run/google/cloud/run_v2/types/revision.py index 4e405041bd95..7900b7af69ab 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/types/revision.py +++ b/packages/google-cloud-run/google/cloud/run_v2/types/revision.py @@ -22,7 +22,7 @@ from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore -from google.cloud.run_v2.types import condition, k8s_min, vendor_settings +from google.cloud.run_v2.types import condition, k8s_min, status, vendor_settings __protobuf__ = proto.module( package="google.cloud.run.v2", @@ -277,6 +277,9 @@ class Revision(proto.Message): Output only. Reserved for future use. session_affinity (bool): Enable session affinity. + scaling_status (google.cloud.run_v2.types.RevisionScalingStatus): + Output only. The current effective scaling + settings for the revision. etag (str): Output only. A system-generated fingerprint for this version of the resource. May be used to @@ -413,6 +416,11 @@ class Revision(proto.Message): proto.BOOL, number=38, ) + scaling_status: status.RevisionScalingStatus = proto.Field( + proto.MESSAGE, + number=39, + message=status.RevisionScalingStatus, + ) etag: str = proto.Field( proto.STRING, number=99, diff --git a/packages/google-cloud-run/google/cloud/run_v2/types/revision_template.py b/packages/google-cloud-run/google/cloud/run_v2/types/revision_template.py index 63366055e61f..e67b2ad5a180 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/types/revision_template.py +++ b/packages/google-cloud-run/google/cloud/run_v2/types/revision_template.py @@ -105,7 +105,10 @@ class RevisionTemplate(proto.Message): Sets the maximum number of requests that each serving instance can receive. session_affinity (bool): - Enable session affinity. + Optional. Enable session affinity. + health_check_disabled (bool): + Optional. Disables health checking containers + during deployment. """ revision: str = proto.Field( @@ -168,6 +171,10 @@ class RevisionTemplate(proto.Message): proto.BOOL, number=19, ) + health_check_disabled: bool = proto.Field( + proto.BOOL, + number=20, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-run/google/cloud/run_v2/types/service.py b/packages/google-cloud-run/google/cloud/run_v2/types/service.py index ec56cec1f649..b2d5f6893d41 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/types/service.py +++ b/packages/google-cloud-run/google/cloud/run_v2/types/service.py @@ -265,11 +265,11 @@ class Service(proto.Message): its JSON representation will be a ``string`` instead of an ``integer``. labels (MutableMapping[str, str]): - Unstructured key value map that can be used to organize and - categorize objects. User-provided labels are shared with - Google's billing system, so they can be used to filter, or - break down billing charges by team, component, environment, - state, etc. For more information, visit + Optional. Unstructured key value map that can be used to + organize and categorize objects. User-provided labels are + shared with Google's billing system, so they can be used to + filter, or break down billing charges by team, component, + environment, state, etc. For more information, visit https://cloud.google.com/resource-manager/docs/creating-managing-labels or https://cloud.google.com/run/docs/configuring/labels. @@ -280,9 +280,9 @@ class Service(proto.Message): namespaces, and they will be rejected. All system labels in v1 now have a corresponding field in v2 Service. annotations (MutableMapping[str, str]): - Unstructured key value map that may be set by external tools - to store and arbitrary metadata. They are not queryable and - should be preserved when modifying objects. + Optional. Unstructured key value map that may be set by + external tools to store and arbitrary metadata. They are not + queryable and should be preserved when modifying objects. .. raw:: html @@ -344,6 +344,12 @@ class Service(proto.Message): Revisions belonging to the Service. If traffic is empty or not provided, defaults to 100% traffic to the latest ``Ready`` Revision. + scaling (google.cloud.run_v2.types.ServiceScaling): + Optional. Specifies service-level scaling + settings + default_uri_disabled (bool): + Optional. Disables public resolution of the + default URI of this service. observed_generation (int): Output only. The generation of this Service currently serving traffic. See comments in ``reconciling`` for @@ -509,6 +515,15 @@ class Service(proto.Message): number=19, message=traffic_target.TrafficTarget, ) + scaling: vendor_settings.ServiceScaling = proto.Field( + proto.MESSAGE, + number=20, + message=vendor_settings.ServiceScaling, + ) + default_uri_disabled: bool = proto.Field( + proto.BOOL, + number=22, + ) observed_generation: int = proto.Field( proto.INT64, number=30, diff --git a/packages/google-cloud-run/google/cloud/run_v2/types/status.py b/packages/google-cloud-run/google/cloud/run_v2/types/status.py new file mode 100644 index 000000000000..aa2108fae6fc --- /dev/null +++ b/packages/google-cloud-run/google/cloud/run_v2/types/status.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.run.v2", + manifest={ + "RevisionScalingStatus", + }, +) + + +class RevisionScalingStatus(proto.Message): + r"""Effective settings for the current revision + + Attributes: + desired_min_instance_count (int): + The current number of min instances + provisioned for this revision. + """ + + desired_min_instance_count: int = proto.Field( + proto.INT32, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-run/google/cloud/run_v2/types/vendor_settings.py b/packages/google-cloud-run/google/cloud/run_v2/types/vendor_settings.py index 64c504199ad3..8906757f363b 100644 --- a/packages/google-cloud-run/google/cloud/run_v2/types/vendor_settings.py +++ b/packages/google-cloud-run/google/cloud/run_v2/types/vendor_settings.py @@ -28,6 +28,7 @@ "VpcAccess", "BinaryAuthorization", "RevisionScaling", + "ServiceScaling", }, ) @@ -232,4 +233,22 @@ class RevisionScaling(proto.Message): ) +class ServiceScaling(proto.Message): + r"""Scaling settings applied at the service level rather than + at the revision level. + + Attributes: + min_instance_count (int): + total min instances for the service. This + number of instances is divided among all + revisions with specified traffic based on the + percent of traffic they are receiving. (BETA) + """ + + min_instance_count: int = proto.Field( + proto.INT32, + number=1, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-run/samples/generated_samples/snippet_metadata_google.cloud.run.v2.json b/packages/google-cloud-run/samples/generated_samples/snippet_metadata_google.cloud.run.v2.json index 06ede518d576..ac5199c95b6e 100644 --- a/packages/google-cloud-run/samples/generated_samples/snippet_metadata_google.cloud.run.v2.json +++ b/packages/google-cloud-run/samples/generated_samples/snippet_metadata_google.cloud.run.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-run", - "version": "0.10.4" + "version": "0.10.5" }, "snippets": [ { diff --git a/packages/google-cloud-run/setup.py b/packages/google-cloud-run/setup.py index c98450541574..99b4648b7487 100644 --- a/packages/google-cloud-run/setup.py +++ b/packages/google-cloud-run/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_jobs.py b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_jobs.py index 2ee46edbbee4..ec4e08e6a5e0 100644 --- a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_jobs.py +++ b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_jobs.py @@ -3084,6 +3084,12 @@ def test_create_job_rest(request_type): "instances": ["instances_value1", "instances_value2"] }, "empty_dir": {"medium": 1, "size_limit": "size_limit_value"}, + "nfs": { + "server": "server_value", + "path": "path_value", + "read_only": True, + }, + "gcs": {"bucket": "bucket_value", "read_only": True}, } ], "max_retries": 1187, @@ -4186,6 +4192,12 @@ def test_update_job_rest(request_type): "instances": ["instances_value1", "instances_value2"] }, "empty_dir": {"medium": 1, "size_limit": "size_limit_value"}, + "nfs": { + "server": "server_value", + "path": "path_value", + "read_only": True, + }, + "gcs": {"bucket": "bucket_value", "read_only": True}, } ], "max_retries": 1187, diff --git a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_revisions.py b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_revisions.py index 2a9ad11ae210..ec57623ad5fa 100644 --- a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_revisions.py +++ b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_revisions.py @@ -62,7 +62,13 @@ pagers, transports, ) -from google.cloud.run_v2.types import condition, k8s_min, revision, vendor_settings +from google.cloud.run_v2.types import ( + condition, + k8s_min, + revision, + status, + vendor_settings, +) def client_cert_source_callback(): diff --git a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_services.py b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_services.py index 4ec047d4fbd1..562b12f53d17 100644 --- a/packages/google-cloud-run/tests/unit/gapic/run_v2/test_services.py +++ b/packages/google-cloud-run/tests/unit/gapic/run_v2/test_services.py @@ -1324,6 +1324,7 @@ def test_get_service(request_type, transport: str = "grpc"): client_version="client_version_value", ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + default_uri_disabled=True, observed_generation=2021, latest_ready_revision="latest_ready_revision_value", latest_created_revision="latest_created_revision_value", @@ -1352,6 +1353,7 @@ def test_get_service(request_type, transport: str = "grpc"): assert response.client_version == "client_version_value" assert response.ingress == vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.default_uri_disabled is True assert response.observed_generation == 2021 assert response.latest_ready_revision == "latest_ready_revision_value" assert response.latest_created_revision == "latest_created_revision_value" @@ -1406,6 +1408,7 @@ async def test_get_service_async( client_version="client_version_value", ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + default_uri_disabled=True, observed_generation=2021, latest_ready_revision="latest_ready_revision_value", latest_created_revision="latest_created_revision_value", @@ -1435,6 +1438,7 @@ async def test_get_service_async( assert response.client_version == "client_version_value" assert response.ingress == vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.default_uri_disabled is True assert response.observed_generation == 2021 assert response.latest_ready_revision == "latest_ready_revision_value" assert response.latest_created_revision == "latest_created_revision_value" @@ -2960,12 +2964,19 @@ def test_create_service_rest(request_type): "instances": ["instances_value1", "instances_value2"] }, "empty_dir": {"medium": 1, "size_limit": "size_limit_value"}, + "nfs": { + "server": "server_value", + "path": "path_value", + "read_only": True, + }, + "gcs": {"bucket": "bucket_value", "read_only": True}, } ], "execution_environment": 1, "encryption_key": "encryption_key_value", "max_instance_request_concurrency": 3436, "session_affinity": True, + "health_check_disabled": True, }, "traffic": [ { @@ -2975,6 +2986,8 @@ def test_create_service_rest(request_type): "tag": "tag_value", } ], + "scaling": {"min_instance_count": 1920}, + "default_uri_disabled": True, "observed_generation": 2021, "terminal_condition": { "type_": "type__value", @@ -3382,6 +3395,7 @@ def test_get_service_rest(request_type): client_version="client_version_value", ingress=vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL, launch_stage=launch_stage_pb2.LaunchStage.UNIMPLEMENTED, + default_uri_disabled=True, observed_generation=2021, latest_ready_revision="latest_ready_revision_value", latest_created_revision="latest_created_revision_value", @@ -3415,6 +3429,7 @@ def test_get_service_rest(request_type): assert response.client_version == "client_version_value" assert response.ingress == vendor_settings.IngressTraffic.INGRESS_TRAFFIC_ALL assert response.launch_stage == launch_stage_pb2.LaunchStage.UNIMPLEMENTED + assert response.default_uri_disabled is True assert response.observed_generation == 2021 assert response.latest_ready_revision == "latest_ready_revision_value" assert response.latest_created_revision == "latest_created_revision_value" @@ -4096,12 +4111,19 @@ def test_update_service_rest(request_type): "instances": ["instances_value1", "instances_value2"] }, "empty_dir": {"medium": 1, "size_limit": "size_limit_value"}, + "nfs": { + "server": "server_value", + "path": "path_value", + "read_only": True, + }, + "gcs": {"bucket": "bucket_value", "read_only": True}, } ], "execution_environment": 1, "encryption_key": "encryption_key_value", "max_instance_request_concurrency": 3436, "session_affinity": True, + "health_check_disabled": True, }, "traffic": [ { @@ -4111,6 +4133,8 @@ def test_update_service_rest(request_type): "tag": "tag_value", } ], + "scaling": {"min_instance_count": 1920}, + "default_uri_disabled": True, "observed_generation": 2021, "terminal_condition": { "type_": "type__value", diff --git a/packages/google-cloud-scheduler/CHANGELOG.md b/packages/google-cloud-scheduler/CHANGELOG.md index a26accec6c16..a98d0aa50fa0 100644 --- a/packages/google-cloud-scheduler/CHANGELOG.md +++ b/packages/google-cloud-scheduler/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-scheduler/#history +## [2.13.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-scheduler-v2.13.2...google-cloud-scheduler-v2.13.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [2.13.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-scheduler-v2.13.1...google-cloud-scheduler-v2.13.2) (2024-02-22) diff --git a/packages/google-cloud-scheduler/google/cloud/scheduler/gapic_version.py b/packages/google-cloud-scheduler/google/cloud/scheduler/gapic_version.py index d767d5ad8591..6c235a092e73 100644 --- a/packages/google-cloud-scheduler/google/cloud/scheduler/gapic_version.py +++ b/packages/google-cloud-scheduler/google/cloud/scheduler/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-scheduler/google/cloud/scheduler_v1/gapic_version.py b/packages/google-cloud-scheduler/google/cloud/scheduler_v1/gapic_version.py index d767d5ad8591..6c235a092e73 100644 --- a/packages/google-cloud-scheduler/google/cloud/scheduler_v1/gapic_version.py +++ b/packages/google-cloud-scheduler/google/cloud/scheduler_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-scheduler/google/cloud/scheduler_v1beta1/gapic_version.py b/packages/google-cloud-scheduler/google/cloud/scheduler_v1beta1/gapic_version.py index d767d5ad8591..6c235a092e73 100644 --- a/packages/google-cloud-scheduler/google/cloud/scheduler_v1beta1/gapic_version.py +++ b/packages/google-cloud-scheduler/google/cloud/scheduler_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-scheduler/samples/generated_samples/snippet_metadata_google.cloud.scheduler.v1.json b/packages/google-cloud-scheduler/samples/generated_samples/snippet_metadata_google.cloud.scheduler.v1.json index e04491577b3b..b8c96c9a11db 100644 --- a/packages/google-cloud-scheduler/samples/generated_samples/snippet_metadata_google.cloud.scheduler.v1.json +++ b/packages/google-cloud-scheduler/samples/generated_samples/snippet_metadata_google.cloud.scheduler.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-scheduler", - "version": "2.13.2" + "version": "2.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-scheduler/samples/generated_samples/snippet_metadata_google.cloud.scheduler.v1beta1.json b/packages/google-cloud-scheduler/samples/generated_samples/snippet_metadata_google.cloud.scheduler.v1beta1.json index 21a60b34b592..bb89749b3d41 100644 --- a/packages/google-cloud-scheduler/samples/generated_samples/snippet_metadata_google.cloud.scheduler.v1beta1.json +++ b/packages/google-cloud-scheduler/samples/generated_samples/snippet_metadata_google.cloud.scheduler.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-scheduler", - "version": "2.13.2" + "version": "2.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-scheduler/setup.py b/packages/google-cloud-scheduler/setup.py index 8d32990486cd..3396c6ed4e4a 100644 --- a/packages/google-cloud-scheduler/setup.py +++ b/packages/google-cloud-scheduler/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-secret-manager/CHANGELOG.md b/packages/google-cloud-secret-manager/CHANGELOG.md index ce28366f76b5..2c8edf815f68 100644 --- a/packages/google-cloud-secret-manager/CHANGELOG.md +++ b/packages/google-cloud-secret-manager/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [2.18.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-secret-manager-v2.18.2...google-cloud-secret-manager-v2.18.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [2.18.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-secret-manager-v2.18.1...google-cloud-secret-manager-v2.18.2) (2024-02-22) diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager/gapic_version.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager/gapic_version.py index 9ddd5e4c0ccb..54cf59ff931b 100644 --- a/packages/google-cloud-secret-manager/google/cloud/secretmanager/gapic_version.py +++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.18.2" # {x-release-please-version} +__version__ = "2.18.3" # {x-release-please-version} diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/gapic_version.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/gapic_version.py index 9ddd5e4c0ccb..54cf59ff931b 100644 --- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/gapic_version.py +++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.18.2" # {x-release-please-version} +__version__ = "2.18.3" # {x-release-please-version} diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1beta1/gapic_version.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1beta1/gapic_version.py index 9ddd5e4c0ccb..54cf59ff931b 100644 --- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1beta1/gapic_version.py +++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.18.2" # {x-release-please-version} +__version__ = "2.18.3" # {x-release-please-version} diff --git a/packages/google-cloud-secret-manager/samples/generated_samples/snippet_metadata_google.cloud.secretmanager.v1.json b/packages/google-cloud-secret-manager/samples/generated_samples/snippet_metadata_google.cloud.secretmanager.v1.json index 8838930ed87f..26d568455dbd 100644 --- a/packages/google-cloud-secret-manager/samples/generated_samples/snippet_metadata_google.cloud.secretmanager.v1.json +++ b/packages/google-cloud-secret-manager/samples/generated_samples/snippet_metadata_google.cloud.secretmanager.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-secret-manager", - "version": "2.18.2" + "version": "2.18.3" }, "snippets": [ { diff --git a/packages/google-cloud-secret-manager/samples/generated_samples/snippet_metadata_google.cloud.secrets.v1beta1.json b/packages/google-cloud-secret-manager/samples/generated_samples/snippet_metadata_google.cloud.secrets.v1beta1.json index b7e932c08f53..ec56253a5993 100644 --- a/packages/google-cloud-secret-manager/samples/generated_samples/snippet_metadata_google.cloud.secrets.v1beta1.json +++ b/packages/google-cloud-secret-manager/samples/generated_samples/snippet_metadata_google.cloud.secrets.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-secretmanager", - "version": "2.18.2" + "version": "2.18.3" }, "snippets": [ { diff --git a/packages/google-cloud-secret-manager/setup.py b/packages/google-cloud-secret-manager/setup.py index 5afece95b2d0..50e2667c6d68 100644 --- a/packages/google-cloud-secret-manager/setup.py +++ b/packages/google-cloud-secret-manager/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-securesourcemanager/CHANGELOG.md b/packages/google-cloud-securesourcemanager/CHANGELOG.md index a62f634f8f2a..77e22573a94d 100644 --- a/packages/google-cloud-securesourcemanager/CHANGELOG.md +++ b/packages/google-cloud-securesourcemanager/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.5](https://github.com/googleapis/google-cloud-python/compare/google-cloud-securesourcemanager-v0.1.4...google-cloud-securesourcemanager-v0.1.5) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [0.1.4](https://github.com/googleapis/google-cloud-python/compare/google-cloud-securesourcemanager-v0.1.3...google-cloud-securesourcemanager-v0.1.4) (2024-02-22) diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager/gapic_version.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager/gapic_version.py index 286ce4ad5531..ae12f4dfd596 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager/gapic_version.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.1.5" # {x-release-please-version} diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/gapic_version.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/gapic_version.py index 286ce4ad5531..ae12f4dfd596 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/gapic_version.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_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.4" # {x-release-please-version} +__version__ = "0.1.5" # {x-release-please-version} diff --git a/packages/google-cloud-securesourcemanager/samples/generated_samples/snippet_metadata_google.cloud.securesourcemanager.v1.json b/packages/google-cloud-securesourcemanager/samples/generated_samples/snippet_metadata_google.cloud.securesourcemanager.v1.json index d54c3ed8f974..202769e559af 100644 --- a/packages/google-cloud-securesourcemanager/samples/generated_samples/snippet_metadata_google.cloud.securesourcemanager.v1.json +++ b/packages/google-cloud-securesourcemanager/samples/generated_samples/snippet_metadata_google.cloud.securesourcemanager.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-securesourcemanager", - "version": "0.1.4" + "version": "0.1.5" }, "snippets": [ { diff --git a/packages/google-cloud-securesourcemanager/setup.py b/packages/google-cloud-securesourcemanager/setup.py index 98b51c071dea..d28b900ff0cb 100644 --- a/packages/google-cloud-securesourcemanager/setup.py +++ b/packages/google-cloud-securesourcemanager/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-securitycenter/CHANGELOG.md b/packages/google-cloud-securitycenter/CHANGELOG.md index 04fe527f5b22..f62e5728bf96 100644 --- a/packages/google-cloud-securitycenter/CHANGELOG.md +++ b/packages/google-cloud-securitycenter/CHANGELOG.md @@ -4,6 +4,20 @@ [1]: https://pypi.org/project/google-cloud-securitycenter/#history +## [1.28.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-securitycenter-v1.27.0...google-cloud-securitycenter-v1.28.0) (2024-03-04) + + +### Features + +* Add container.create_time, vulnerability.offending_package, vulnerability.fixed_package, vulnerability.security_bulletin, vulnerability.cve.impact, vulnerability.cve.exploitation_activity, vulnerability.cve.observed_in_the_wild, vulnerability.cve.zero_day to finding's list of attributes ([4450f4c](https://github.com/googleapis/google-cloud-python/commit/4450f4ce787d11cfa11934dbd2acfe194474ca32)) +* Add load balancer, log entry, org policy, database.version, exfiltration.total_exfiltrated_bytes, file.disk_path, indicator.signature_type, and kubernetes.objects to finding's list of attributes ([4450f4c](https://github.com/googleapis/google-cloud-python/commit/4450f4ce787d11cfa11934dbd2acfe194474ca32)) +* Added security center api V2 client library ([4450f4c](https://github.com/googleapis/google-cloud-python/commit/4450f4ce787d11cfa11934dbd2acfe194474ca32)) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([4450f4c](https://github.com/googleapis/google-cloud-python/commit/4450f4ce787d11cfa11934dbd2acfe194474ca32)) + ## [1.27.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-securitycenter-v1.26.1...google-cloud-securitycenter-v1.27.0) (2024-02-22) diff --git a/packages/google-cloud-securitycenter/docs/index.rst b/packages/google-cloud-securitycenter/docs/index.rst index 3d7c999e8772..34ebeb002c30 100644 --- a/packages/google-cloud-securitycenter/docs/index.rst +++ b/packages/google-cloud-securitycenter/docs/index.rst @@ -30,6 +30,14 @@ API Reference securitycenter_v1p1beta1/services_ securitycenter_v1p1beta1/types_ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + securitycenter_v2/services_ + securitycenter_v2/types_ + Changelog --------- diff --git a/packages/google-cloud-securitycenter/docs/securitycenter_v2/security_center.rst b/packages/google-cloud-securitycenter/docs/securitycenter_v2/security_center.rst new file mode 100644 index 000000000000..6b9d3b9b1795 --- /dev/null +++ b/packages/google-cloud-securitycenter/docs/securitycenter_v2/security_center.rst @@ -0,0 +1,10 @@ +SecurityCenter +-------------------------------- + +.. automodule:: google.cloud.securitycenter_v2.services.security_center + :members: + :inherited-members: + +.. automodule:: google.cloud.securitycenter_v2.services.security_center.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-securitycenter/docs/securitycenter_v2/services_.rst b/packages/google-cloud-securitycenter/docs/securitycenter_v2/services_.rst new file mode 100644 index 000000000000..adb8a6096090 --- /dev/null +++ b/packages/google-cloud-securitycenter/docs/securitycenter_v2/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Securitycenter v2 API +=============================================== +.. toctree:: + :maxdepth: 2 + + security_center diff --git a/packages/google-cloud-securitycenter/docs/securitycenter_v2/types_.rst b/packages/google-cloud-securitycenter/docs/securitycenter_v2/types_.rst new file mode 100644 index 000000000000..3210d372fb24 --- /dev/null +++ b/packages/google-cloud-securitycenter/docs/securitycenter_v2/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Securitycenter v2 API +============================================ + +.. automodule:: google.cloud.securitycenter_v2.types + :members: + :show-inheritance: diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter/__init__.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter/__init__.py index 046271412037..9444e7513937 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter/__init__.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter/__init__.py @@ -60,12 +60,15 @@ from google.cloud.securitycenter_v1.types.kernel_rootkit import KernelRootkit from google.cloud.securitycenter_v1.types.kubernetes import Kubernetes from google.cloud.securitycenter_v1.types.label import Label +from google.cloud.securitycenter_v1.types.load_balancer import LoadBalancer +from google.cloud.securitycenter_v1.types.log_entry import CloudLoggingEntry, LogEntry from google.cloud.securitycenter_v1.types.mitre_attack import MitreAttack from google.cloud.securitycenter_v1.types.mute_config import MuteConfig from google.cloud.securitycenter_v1.types.notification_config import NotificationConfig from google.cloud.securitycenter_v1.types.notification_message import ( NotificationMessage, ) +from google.cloud.securitycenter_v1.types.org_policy import OrgPolicy from google.cloud.securitycenter_v1.types.organization_settings import ( OrganizationSettings, ) @@ -143,7 +146,9 @@ from google.cloud.securitycenter_v1.types.vulnerability import ( Cve, Cvssv3, + Package, Reference, + SecurityBulletin, Vulnerability, ) @@ -177,10 +182,14 @@ "KernelRootkit", "Kubernetes", "Label", + "LoadBalancer", + "CloudLoggingEntry", + "LogEntry", "MitreAttack", "MuteConfig", "NotificationConfig", "NotificationMessage", + "OrgPolicy", "OrganizationSettings", "EnvironmentVariable", "Process", @@ -248,6 +257,8 @@ "Source", "Cve", "Cvssv3", + "Package", "Reference", + "SecurityBulletin", "Vulnerability", ) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter/gapic_version.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter/gapic_version.py index 484507c567a0..251e3720307c 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter/gapic_version.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.27.0" # {x-release-please-version} +__version__ = "1.28.0" # {x-release-please-version} diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/__init__.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/__init__.py index eb619350b025..b9cc2f203140 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/__init__.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/__init__.py @@ -44,10 +44,13 @@ from .types.kernel_rootkit import KernelRootkit from .types.kubernetes import Kubernetes from .types.label import Label +from .types.load_balancer import LoadBalancer +from .types.log_entry import CloudLoggingEntry, LogEntry from .types.mitre_attack import MitreAttack from .types.mute_config import MuteConfig from .types.notification_config import NotificationConfig from .types.notification_message import NotificationMessage +from .types.org_policy import OrgPolicy from .types.organization_settings import OrganizationSettings from .types.process import EnvironmentVariable, Process from .types.resource import Resource @@ -116,7 +119,14 @@ UpdateSourceRequest, ) from .types.source import Source -from .types.vulnerability import Cve, Cvssv3, Reference, Vulnerability +from .types.vulnerability import ( + Cve, + Cvssv3, + Package, + Reference, + SecurityBulletin, + Vulnerability, +) __all__ = ( "SecurityCenterAsyncClient", @@ -129,6 +139,7 @@ "BulkMuteFindingsResponse", "CloudDlpDataProfile", "CloudDlpInspection", + "CloudLoggingEntry", "Compliance", "Connection", "Contact", @@ -192,16 +203,21 @@ "ListSecurityHealthAnalyticsCustomModulesResponse", "ListSourcesRequest", "ListSourcesResponse", + "LoadBalancer", + "LogEntry", "MitreAttack", "MuteConfig", "NotificationConfig", "NotificationMessage", + "OrgPolicy", "OrganizationSettings", + "Package", "Process", "Reference", "Resource", "RunAssetDiscoveryRequest", "RunAssetDiscoveryResponse", + "SecurityBulletin", "SecurityCenterClient", "SecurityHealthAnalyticsCustomModule", "SecurityMarks", diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/gapic_version.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/gapic_version.py index 484507c567a0..251e3720307c 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/gapic_version.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.27.0" # {x-release-please-version} +__version__ = "1.28.0" # {x-release-please-version} diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/async_client.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/async_client.py index a5e58e188f46..b70a5aba8b75 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/async_client.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/async_client.py @@ -77,6 +77,8 @@ indicator, kernel_rootkit, kubernetes, + load_balancer, + log_entry, mitre_attack, ) from google.cloud.securitycenter_v1.types import external_system as gcs_external_system @@ -97,6 +99,7 @@ from google.cloud.securitycenter_v1.types import mute_config from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import org_policy from google.cloud.securitycenter_v1.types import organization_settings from google.cloud.securitycenter_v1.types import security_marks from google.cloud.securitycenter_v1.types import securitycenter_service @@ -155,6 +158,8 @@ class SecurityCenterAsyncClient: parse_organization_settings_path = staticmethod( SecurityCenterClient.parse_organization_settings_path ) + policy_path = staticmethod(SecurityCenterClient.policy_path) + parse_policy_path = staticmethod(SecurityCenterClient.parse_policy_path) security_health_analytics_custom_module_path = staticmethod( SecurityCenterClient.security_health_analytics_custom_module_path ) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/client.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/client.py index 0c7a98d8a626..04459fd18a8e 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/client.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/client.py @@ -81,6 +81,8 @@ indicator, kernel_rootkit, kubernetes, + load_balancer, + log_entry, mitre_attack, ) from google.cloud.securitycenter_v1.types import external_system as gcs_external_system @@ -101,6 +103,7 @@ from google.cloud.securitycenter_v1.types import mute_config from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import org_policy from google.cloud.securitycenter_v1.types import organization_settings from google.cloud.securitycenter_v1.types import security_marks from google.cloud.securitycenter_v1.types import securitycenter_service @@ -423,6 +426,26 @@ def parse_organization_settings_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def policy_path( + organization: str, + constraint_name: str, + ) -> str: + """Returns a fully-qualified policy string.""" + return "organizations/{organization}/policies/{constraint_name}".format( + organization=organization, + constraint_name=constraint_name, + ) + + @staticmethod + def parse_policy_path(path: str) -> Dict[str, str]: + """Parses a policy path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/policies/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def security_health_analytics_custom_module_path( organization: str, diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/__init__.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/__init__.py index 8da5695c7bbd..f25774026695 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/__init__.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/__init__.py @@ -38,10 +38,13 @@ from .kernel_rootkit import KernelRootkit from .kubernetes import Kubernetes from .label import Label +from .load_balancer import LoadBalancer +from .log_entry import CloudLoggingEntry, LogEntry from .mitre_attack import MitreAttack from .mute_config import MuteConfig from .notification_config import NotificationConfig from .notification_message import NotificationMessage +from .org_policy import OrgPolicy from .organization_settings import OrganizationSettings from .process import EnvironmentVariable, Process from .resource import Resource @@ -108,7 +111,14 @@ UpdateSourceRequest, ) from .source import Source -from .vulnerability import Cve, Cvssv3, Reference, Vulnerability +from .vulnerability import ( + Cve, + Cvssv3, + Package, + Reference, + SecurityBulletin, + Vulnerability, +) __all__ = ( "Access", @@ -138,10 +148,14 @@ "KernelRootkit", "Kubernetes", "Label", + "LoadBalancer", + "CloudLoggingEntry", + "LogEntry", "MitreAttack", "MuteConfig", "NotificationConfig", "NotificationMessage", + "OrgPolicy", "OrganizationSettings", "EnvironmentVariable", "Process", @@ -209,6 +223,8 @@ "Source", "Cve", "Cvssv3", + "Package", "Reference", + "SecurityBulletin", "Vulnerability", ) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/container.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/container.py index 1a005bb78739..f76c885b3c38 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/container.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/container.py @@ -17,6 +17,7 @@ from typing import MutableMapping, MutableSequence +from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore from google.cloud.securitycenter_v1.types import label @@ -47,6 +48,8 @@ class Container(proto.Message): labels (MutableSequence[google.cloud.securitycenter_v1.types.Label]): Container labels, as provided by the container runtime. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time that the container was created. """ name: str = proto.Field( @@ -66,6 +69,11 @@ class Container(proto.Message): number=4, message=label.Label, ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/database.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/database.py index 5eb7c3f3011c..2a1ed6e5cdd7 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/database.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/database.py @@ -35,16 +35,16 @@ class Database(proto.Message): name `__ populated because these resource types, such as Cloud SQL databases, are not yet supported by Cloud Asset Inventory. In these cases only the - display name is provided. Some database resources may not have the - `full resource - name `__ populated - because these resource types are not yet supported by Cloud Asset - Inventory (e.g. Cloud SQL databases). In these cases only the - display name will be provided. + display name is provided. Attributes: name (str): - The `full resource + Some database resources may not have the `full resource + name `__ + populated because these resource types are not yet supported + by Cloud Asset Inventory (e.g. Cloud SQL databases). In + these cases only the display name will be provided. The + `full resource name `__ of the database that the user connected to, if it is supported by Cloud Asset Inventory. @@ -62,6 +62,10 @@ class Database(proto.Message): The target usernames, roles, or groups of an SQL privilege grant, which is not an IAM policy change. + version (str): + The version of the database, for example, POSTGRES_14. See + `the complete + list `__. """ name: str = proto.Field( @@ -84,6 +88,10 @@ class Database(proto.Message): proto.STRING, number=5, ) + version: str = proto.Field( + proto.STRING, + number=6, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/exfiltration.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/exfiltration.py index 8ec6b1787f26..3147dae302a9 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/exfiltration.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/exfiltration.py @@ -44,6 +44,9 @@ class Exfiltration(proto.Message): If there are multiple targets, each target would get a complete copy of the "joined" source data. + total_exfiltrated_bytes (int): + Total exfiltrated bytes processed for the + entire job. """ sources: MutableSequence["ExfilResource"] = proto.RepeatedField( @@ -56,6 +59,10 @@ class Exfiltration(proto.Message): number=2, message="ExfilResource", ) + total_exfiltrated_bytes: int = proto.Field( + proto.INT64, + number=3, + ) class ExfilResource(proto.Message): diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/file.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/file.py index aeea18dc7b8b..a44d5508acf5 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/file.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/file.py @@ -51,8 +51,33 @@ class File(proto.Message): contents (str): Prefix of the file contents as a JSON-encoded string. + disk_path (google.cloud.securitycenter_v1.types.File.DiskPath): + Path of the file in terms of underlying + disk/partition identifiers. """ + class DiskPath(proto.Message): + r"""Path of the file in terms of underlying disk/partition + identifiers. + + Attributes: + partition_uuid (str): + UUID of the partition (format + https://wiki.archlinux.org/title/persistent_block_device_naming#by-uuid) + relative_path (str): + Relative path of the file in the partition as a JSON encoded + string. Example: /home/user1/executable_file.sh + """ + + partition_uuid: str = proto.Field( + proto.STRING, + number=1, + ) + relative_path: str = proto.Field( + proto.STRING, + number=2, + ) + path: str = proto.Field( proto.STRING, number=1, @@ -77,6 +102,11 @@ class File(proto.Message): proto.STRING, number=6, ) + disk_path: DiskPath = proto.Field( + proto.MESSAGE, + number=7, + message=DiskPath, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/finding.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/finding.py index 5bec59aa5011..e78da17c161c 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/finding.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/finding.py @@ -47,7 +47,8 @@ from google.cloud.securitycenter_v1.types import database as gcs_database from google.cloud.securitycenter_v1.types import indicator as gcs_indicator from google.cloud.securitycenter_v1.types import kubernetes as gcs_kubernetes -from google.cloud.securitycenter_v1.types import process +from google.cloud.securitycenter_v1.types import load_balancer, log_entry +from google.cloud.securitycenter_v1.types import org_policy, process __protobuf__ = proto.module( package="google.cloud.securitycenter.v1", @@ -242,11 +243,19 @@ class Finding(proto.Message): with the finding. kernel_rootkit (google.cloud.securitycenter_v1.types.KernelRootkit): Signature of the kernel rootkit. + org_policies (MutableSequence[google.cloud.securitycenter_v1.types.OrgPolicy]): + Contains information about the org policies + associated with the finding. application (google.cloud.securitycenter_v1.types.Application): Represents an application associated with the finding. backup_disaster_recovery (google.cloud.securitycenter_v1.types.BackupDisasterRecovery): Fields related to Backup and DR findings. + log_entries (MutableSequence[google.cloud.securitycenter_v1.types.LogEntry]): + Log entries that are relevant to the finding. + load_balancers (MutableSequence[google.cloud.securitycenter_v1.types.LoadBalancer]): + The load balancers associated with the + finding. """ class State(proto.Enum): @@ -589,6 +598,11 @@ class FindingClass(proto.Enum): number=50, message=gcs_kernel_rootkit.KernelRootkit, ) + org_policies: MutableSequence[org_policy.OrgPolicy] = proto.RepeatedField( + proto.MESSAGE, + number=51, + message=org_policy.OrgPolicy, + ) application: gcs_application.Application = proto.Field( proto.MESSAGE, number=53, @@ -601,6 +615,16 @@ class FindingClass(proto.Enum): message=gcs_backup_disaster_recovery.BackupDisasterRecovery, ) ) + log_entries: MutableSequence[log_entry.LogEntry] = proto.RepeatedField( + proto.MESSAGE, + number=57, + message=log_entry.LogEntry, + ) + load_balancers: MutableSequence[load_balancer.LoadBalancer] = proto.RepeatedField( + proto.MESSAGE, + number=58, + message=load_balancer.LoadBalancer, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/indicator.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/indicator.py index 46f5254b8db5..4aa358a985bf 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/indicator.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/indicator.py @@ -70,8 +70,26 @@ class ProcessSignature(proto.Message): matched. This field is a member of `oneof`_ ``signature``. + signature_type (google.cloud.securitycenter_v1.types.Indicator.ProcessSignature.SignatureType): + Describes the type of resource associated + with the signature. """ + class SignatureType(proto.Enum): + r"""Possible resource types to be associated with a signature. + + Values: + SIGNATURE_TYPE_UNSPECIFIED (0): + The default signature type. + SIGNATURE_TYPE_PROCESS (1): + Used for signatures concerning processes. + SIGNATURE_TYPE_FILE (2): + Used for signatures concerning disks. + """ + SIGNATURE_TYPE_UNSPECIFIED = 0 + SIGNATURE_TYPE_PROCESS = 1 + SIGNATURE_TYPE_FILE = 2 + class MemoryHashSignature(proto.Message): r"""A signature corresponding to memory page hashes. @@ -146,6 +164,11 @@ class YaraRuleSignature(proto.Message): message="Indicator.ProcessSignature.YaraRuleSignature", ) ) + signature_type: "Indicator.ProcessSignature.SignatureType" = proto.Field( + proto.ENUM, + number=8, + enum="Indicator.ProcessSignature.SignatureType", + ) ip_addresses: MutableSequence[str] = proto.RepeatedField( proto.STRING, diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/kubernetes.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/kubernetes.py index fc4436f4b083..f482daa0f639 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/kubernetes.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/kubernetes.py @@ -59,6 +59,8 @@ class Kubernetes(proto.Message): Provides information on any Kubernetes access reviews (privilege checks) relevant to the finding. + objects (MutableSequence[google.cloud.securitycenter_v1.types.Kubernetes.Object]): + Kubernetes objects related to the finding. """ class Pod(proto.Message): @@ -310,6 +312,52 @@ class AccessReview(proto.Message): number=7, ) + class Object(proto.Message): + r"""Kubernetes object related to the finding, uniquely identified + by GKNN. Used if the object Kind is not one of Pod, Node, + NodePool, Binding, or AccessReview. + + Attributes: + group (str): + Kubernetes object group, such as + "policy.k8s.io/v1". + kind (str): + Kubernetes object kind, such as "Namespace". + ns (str): + Kubernetes object namespace. Must be a valid + DNS label. Named "ns" to avoid collision with + C++ namespace keyword. For details see + https://kubernetes.io/docs/tasks/administer-cluster/namespaces/. + name (str): + Kubernetes object name. For details see + https://kubernetes.io/docs/concepts/overview/working-with-objects/names/. + containers (MutableSequence[google.cloud.securitycenter_v1.types.Container]): + Pod containers associated with this finding, + if any. + """ + + group: str = proto.Field( + proto.STRING, + number=1, + ) + kind: str = proto.Field( + proto.STRING, + number=2, + ) + ns: str = proto.Field( + proto.STRING, + number=3, + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + containers: MutableSequence[container.Container] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=container.Container, + ) + pods: MutableSequence[Pod] = proto.RepeatedField( proto.MESSAGE, number=1, @@ -340,6 +388,11 @@ class AccessReview(proto.Message): number=6, message=AccessReview, ) + objects: MutableSequence[Object] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Object, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/load_balancer.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/load_balancer.py new file mode 100644 index 000000000000..ef34b965e550 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/load_balancer.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v1", + manifest={ + "LoadBalancer", + }, +) + + +class LoadBalancer(proto.Message): + r"""Contains information related to the load balancer associated + with the finding. + + Attributes: + name (str): + The name of the load balancer associated with + the finding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/log_entry.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/log_entry.py new file mode 100644 index 000000000000..8157df9dc4b9 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/log_entry.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v1", + manifest={ + "LogEntry", + "CloudLoggingEntry", + }, +) + + +class LogEntry(proto.Message): + r"""An individual entry in a log. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_logging_entry (google.cloud.securitycenter_v1.types.CloudLoggingEntry): + An individual entry in a log stored in Cloud + Logging. + + This field is a member of `oneof`_ ``log_entry``. + """ + + cloud_logging_entry: "CloudLoggingEntry" = proto.Field( + proto.MESSAGE, + number=1, + oneof="log_entry", + message="CloudLoggingEntry", + ) + + +class CloudLoggingEntry(proto.Message): + r"""Metadata taken from a `Cloud Logging + LogEntry `__ + + Attributes: + insert_id (str): + A unique identifier for the log entry. + log_id (str): + The type of the log (part of ``log_name``. ``log_name`` is + the resource name of the log to which this log entry + belongs). For example: + ``cloudresourcemanager.googleapis.com/activity``. Note that + this field is not URL-encoded, unlike the ``LOG_ID`` field + in ``LogEntry``. + resource_container (str): + The organization, folder, or project of the + monitored resource that produced this log entry. + timestamp (google.protobuf.timestamp_pb2.Timestamp): + The time the event described by the log entry + occurred. + """ + + insert_id: str = proto.Field( + proto.STRING, + number=1, + ) + log_id: str = proto.Field( + proto.STRING, + number=2, + ) + resource_container: str = proto.Field( + proto.STRING, + number=3, + ) + timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/mitre_attack.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/mitre_attack.py index 75d28ce0faa2..6b340c329b7f 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/mitre_attack.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/mitre_attack.py @@ -111,117 +111,187 @@ class Tactic(proto.Enum): class Technique(proto.Enum): r"""MITRE ATT&CK techniques that can be referenced by SCC findings. See: https://attack.mitre.org/techniques/enterprise/ + Next ID: 59 Values: TECHNIQUE_UNSPECIFIED (0): Unspecified value. - ACTIVE_SCANNING (1): - T1595 - SCANNING_IP_BLOCKS (2): - T1595.001 - INGRESS_TOOL_TRANSFER (3): - T1105 - NATIVE_API (4): - T1106 - SHARED_MODULES (5): - T1129 + MASQUERADING (49): + T1036 + MATCH_LEGITIMATE_NAME_OR_LOCATION (50): + T1036.005 + BOOT_OR_LOGON_INITIALIZATION_SCRIPTS (37): + T1037 + STARTUP_ITEMS (38): + T1037.005 + NETWORK_SERVICE_DISCOVERY (32): + T1046 + PROCESS_DISCOVERY (56): + T1057 COMMAND_AND_SCRIPTING_INTERPRETER (6): T1059 UNIX_SHELL (7): T1059.004 - RESOURCE_HIJACKING (8): - T1496 - PROXY (9): - T1090 - EXTERNAL_PROXY (10): - T1090.002 - MULTI_HOP_PROXY (11): - T1090.003 - DYNAMIC_RESOLUTION (12): - T1568 - UNSECURED_CREDENTIALS (13): - T1552 + PERMISSION_GROUPS_DISCOVERY (18): + T1069 + CLOUD_GROUPS (19): + T1069.003 + APPLICATION_LAYER_PROTOCOL (45): + T1071 + DNS (46): + T1071.004 + SOFTWARE_DEPLOYMENT_TOOLS (47): + T1072 VALID_ACCOUNTS (14): T1078 + DEFAULT_ACCOUNTS (35): + T1078.001 LOCAL_ACCOUNTS (15): T1078.003 CLOUD_ACCOUNTS (16): T1078.004 - NETWORK_DENIAL_OF_SERVICE (17): - T1498 - PERMISSION_GROUPS_DISCOVERY (18): - T1069 - CLOUD_GROUPS (19): - T1069.003 - EXFILTRATION_OVER_WEB_SERVICE (20): - T1567 - EXFILTRATION_TO_CLOUD_STORAGE (21): - T1567.002 + PROXY (9): + T1090 + EXTERNAL_PROXY (10): + T1090.002 + MULTI_HOP_PROXY (11): + T1090.003 ACCOUNT_MANIPULATION (22): T1098 + ADDITIONAL_CLOUD_CREDENTIALS (40): + T1098.001 SSH_AUTHORIZED_KEYS (23): T1098.004 - CREATE_OR_MODIFY_SYSTEM_PROCESS (24): - T1543 - STEAL_WEB_SESSION_COOKIE (25): - T1539 - MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE (26): - T1578 + ADDITIONAL_CONTAINER_CLUSTER_ROLES (58): + T1098.006 + INGRESS_TOOL_TRANSFER (3): + T1105 + NATIVE_API (4): + T1106 + BRUTE_FORCE (44): + T1110 + SHARED_MODULES (5): + T1129 + ACCESS_TOKEN_MANIPULATION (33): + T1134 + TOKEN_IMPERSONATION_OR_THEFT (39): + T1134.001 EXPLOIT_PUBLIC_FACING_APPLICATION (27): T1190 - MODIFY_AUTHENTICATION_PROCESS (28): - T1556 - DATA_DESTRUCTION (29): - T1485 DOMAIN_POLICY_MODIFICATION (30): T1484 - IMPAIR_DEFENSES (31): - T1562 - NETWORK_SERVICE_DISCOVERY (32): - T1046 - ACCESS_TOKEN_MANIPULATION (33): - T1134 + DATA_DESTRUCTION (29): + T1485 + SERVICE_STOP (52): + T1489 + INHIBIT_SYSTEM_RECOVERY (36): + T1490 + RESOURCE_HIJACKING (8): + T1496 + NETWORK_DENIAL_OF_SERVICE (17): + T1498 + CLOUD_SERVICE_DISCOVERY (48): + T1526 + STEAL_APPLICATION_ACCESS_TOKEN (42): + T1528 + ACCOUNT_ACCESS_REMOVAL (51): + T1531 + STEAL_WEB_SESSION_COOKIE (25): + T1539 + CREATE_OR_MODIFY_SYSTEM_PROCESS (24): + T1543 ABUSE_ELEVATION_CONTROL_MECHANISM (34): T1548 - DEFAULT_ACCOUNTS (35): - T1078.001 + UNSECURED_CREDENTIALS (13): + T1552 + MODIFY_AUTHENTICATION_PROCESS (28): + T1556 + IMPAIR_DEFENSES (31): + T1562 + DISABLE_OR_MODIFY_TOOLS (55): + T1562.001 + EXFILTRATION_OVER_WEB_SERVICE (20): + T1567 + EXFILTRATION_TO_CLOUD_STORAGE (21): + T1567.002 + DYNAMIC_RESOLUTION (12): + T1568 + LATERAL_TOOL_TRANSFER (41): + T1570 + MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE (26): + T1578 + CREATE_SNAPSHOT (54): + T1578.001 + CLOUD_INFRASTRUCTURE_DISCOVERY (53): + T1580 + OBTAIN_CAPABILITIES (43): + T1588 + ACTIVE_SCANNING (1): + T1595 + SCANNING_IP_BLOCKS (2): + T1595.001 + CONTAINER_AND_RESOURCE_DISCOVERY (57): + T1613 """ TECHNIQUE_UNSPECIFIED = 0 - ACTIVE_SCANNING = 1 - SCANNING_IP_BLOCKS = 2 - INGRESS_TOOL_TRANSFER = 3 - NATIVE_API = 4 - SHARED_MODULES = 5 + MASQUERADING = 49 + MATCH_LEGITIMATE_NAME_OR_LOCATION = 50 + BOOT_OR_LOGON_INITIALIZATION_SCRIPTS = 37 + STARTUP_ITEMS = 38 + NETWORK_SERVICE_DISCOVERY = 32 + PROCESS_DISCOVERY = 56 COMMAND_AND_SCRIPTING_INTERPRETER = 6 UNIX_SHELL = 7 - RESOURCE_HIJACKING = 8 - PROXY = 9 - EXTERNAL_PROXY = 10 - MULTI_HOP_PROXY = 11 - DYNAMIC_RESOLUTION = 12 - UNSECURED_CREDENTIALS = 13 + PERMISSION_GROUPS_DISCOVERY = 18 + CLOUD_GROUPS = 19 + APPLICATION_LAYER_PROTOCOL = 45 + DNS = 46 + SOFTWARE_DEPLOYMENT_TOOLS = 47 VALID_ACCOUNTS = 14 + DEFAULT_ACCOUNTS = 35 LOCAL_ACCOUNTS = 15 CLOUD_ACCOUNTS = 16 - NETWORK_DENIAL_OF_SERVICE = 17 - PERMISSION_GROUPS_DISCOVERY = 18 - CLOUD_GROUPS = 19 - EXFILTRATION_OVER_WEB_SERVICE = 20 - EXFILTRATION_TO_CLOUD_STORAGE = 21 + PROXY = 9 + EXTERNAL_PROXY = 10 + MULTI_HOP_PROXY = 11 ACCOUNT_MANIPULATION = 22 + ADDITIONAL_CLOUD_CREDENTIALS = 40 SSH_AUTHORIZED_KEYS = 23 - CREATE_OR_MODIFY_SYSTEM_PROCESS = 24 - STEAL_WEB_SESSION_COOKIE = 25 - MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE = 26 + ADDITIONAL_CONTAINER_CLUSTER_ROLES = 58 + INGRESS_TOOL_TRANSFER = 3 + NATIVE_API = 4 + BRUTE_FORCE = 44 + SHARED_MODULES = 5 + ACCESS_TOKEN_MANIPULATION = 33 + TOKEN_IMPERSONATION_OR_THEFT = 39 EXPLOIT_PUBLIC_FACING_APPLICATION = 27 - MODIFY_AUTHENTICATION_PROCESS = 28 - DATA_DESTRUCTION = 29 DOMAIN_POLICY_MODIFICATION = 30 - IMPAIR_DEFENSES = 31 - NETWORK_SERVICE_DISCOVERY = 32 - ACCESS_TOKEN_MANIPULATION = 33 + DATA_DESTRUCTION = 29 + SERVICE_STOP = 52 + INHIBIT_SYSTEM_RECOVERY = 36 + RESOURCE_HIJACKING = 8 + NETWORK_DENIAL_OF_SERVICE = 17 + CLOUD_SERVICE_DISCOVERY = 48 + STEAL_APPLICATION_ACCESS_TOKEN = 42 + ACCOUNT_ACCESS_REMOVAL = 51 + STEAL_WEB_SESSION_COOKIE = 25 + CREATE_OR_MODIFY_SYSTEM_PROCESS = 24 ABUSE_ELEVATION_CONTROL_MECHANISM = 34 - DEFAULT_ACCOUNTS = 35 + UNSECURED_CREDENTIALS = 13 + MODIFY_AUTHENTICATION_PROCESS = 28 + IMPAIR_DEFENSES = 31 + DISABLE_OR_MODIFY_TOOLS = 55 + EXFILTRATION_OVER_WEB_SERVICE = 20 + EXFILTRATION_TO_CLOUD_STORAGE = 21 + DYNAMIC_RESOLUTION = 12 + LATERAL_TOOL_TRANSFER = 41 + MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE = 26 + CREATE_SNAPSHOT = 54 + CLOUD_INFRASTRUCTURE_DISCOVERY = 53 + OBTAIN_CAPABILITIES = 43 + ACTIVE_SCANNING = 1 + SCANNING_IP_BLOCKS = 2 + CONTAINER_AND_RESOURCE_DISCOVERY = 57 primary_tactic: Tactic = proto.Field( proto.ENUM, diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/org_policy.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/org_policy.py new file mode 100644 index 000000000000..5845b4634e2b --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/org_policy.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v1", + manifest={ + "OrgPolicy", + }, +) + + +class OrgPolicy(proto.Message): + r"""Contains information about the org policies associated with + the finding. + + Attributes: + name (str): + The resource name of the org policy. Example: + "organizations/{organization_id}/policies/{constraint_name}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/source.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/source.py index d166df568420..55b6df83177d 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/source.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/source.py @@ -58,9 +58,9 @@ class Source(proto.Message): mixed content (HTTP in HTTPS), and outdated or insecure libraries.". canonical_name (str): - The canonical name of the finding. It's either + The canonical name of the finding source. It's either "organizations/{organization_id}/sources/{source_id}", - "folders/{folder_id}/sources/{source_id}" or + "folders/{folder_id}/sources/{source_id}", or "projects/{project_number}/sources/{source_id}", depending on the closest CRM ancestor of the resource associated with the finding. diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/vulnerability.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/vulnerability.py index a9fea0e6bca2..80a1d551bd78 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/vulnerability.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/vulnerability.py @@ -17,6 +17,7 @@ from typing import MutableMapping, MutableSequence +from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore __protobuf__ = proto.module( @@ -26,6 +27,8 @@ "Cve", "Reference", "Cvssv3", + "Package", + "SecurityBulletin", }, ) @@ -38,6 +41,14 @@ class Vulnerability(proto.Message): cve (google.cloud.securitycenter_v1.types.Cve): CVE stands for Common Vulnerabilities and Exposures (https://cve.mitre.org/about/) + offending_package (google.cloud.securitycenter_v1.types.Package): + The offending package is relevant to the + finding. + fixed_package (google.cloud.securitycenter_v1.types.Package): + The fixed package is relevant to the finding. + security_bulletin (google.cloud.securitycenter_v1.types.SecurityBulletin): + The security bulletin is relevant to this + finding. """ cve: "Cve" = proto.Field( @@ -45,11 +56,28 @@ class Vulnerability(proto.Message): number=1, message="Cve", ) + offending_package: "Package" = proto.Field( + proto.MESSAGE, + number=2, + message="Package", + ) + fixed_package: "Package" = proto.Field( + proto.MESSAGE, + number=3, + message="Package", + ) + security_bulletin: "SecurityBulletin" = proto.Field( + proto.MESSAGE, + number=4, + message="SecurityBulletin", + ) class Cve(proto.Message): - r"""CVE stands for Common Vulnerabilities and Exposures. - More information: https://cve.mitre.org + r"""CVE stands for Common Vulnerabilities and Exposures. Information + from the `CVE + record `__ that + describes this vulnerability. Attributes: id (str): @@ -66,8 +94,80 @@ class Cve(proto.Message): upstream_fix_available (bool): Whether upstream fix is available for the CVE. + impact (google.cloud.securitycenter_v1.types.Cve.RiskRating): + The potential impact of the vulnerability if + it was to be exploited. + exploitation_activity (google.cloud.securitycenter_v1.types.Cve.ExploitationActivity): + The exploitation activity of the + vulnerability in the wild. + observed_in_the_wild (bool): + Whether or not the vulnerability has been + observed in the wild. + zero_day (bool): + Whether or not the vulnerability was zero day + when the finding was published. """ + class RiskRating(proto.Enum): + r"""The possible values of impact of the vulnerability if it was + to be exploited. + + Values: + RISK_RATING_UNSPECIFIED (0): + Invalid or empty value. + LOW (1): + Exploitation would have little to no security + impact. + MEDIUM (2): + Exploitation would enable attackers to + perform activities, or could allow attackers to + have a direct impact, but would require + additional steps. + HIGH (3): + Exploitation would enable attackers to have a + notable direct impact without needing to + overcome any major mitigating factors. + CRITICAL (4): + Exploitation would fundamentally undermine + the security of affected systems, enable actors + to perform significant attacks with minimal + effort, with little to no mitigating factors to + overcome. + """ + RISK_RATING_UNSPECIFIED = 0 + LOW = 1 + MEDIUM = 2 + HIGH = 3 + CRITICAL = 4 + + class ExploitationActivity(proto.Enum): + r"""The possible values of exploitation activity of the + vulnerability in the wild. + + Values: + EXPLOITATION_ACTIVITY_UNSPECIFIED (0): + Invalid or empty value. + WIDE (1): + Exploitation has been reported or confirmed + to widely occur. + CONFIRMED (2): + Limited reported or confirmed exploitation + activities. + AVAILABLE (3): + Exploit is publicly available. + ANTICIPATED (4): + No known exploitation activity, but has a + high potential for exploitation. + NO_KNOWN (5): + No known exploitation activity. + """ + EXPLOITATION_ACTIVITY_UNSPECIFIED = 0 + WIDE = 1 + CONFIRMED = 2 + AVAILABLE = 3 + ANTICIPATED = 4 + NO_KNOWN = 5 + id: str = proto.Field( proto.STRING, number=1, @@ -86,6 +186,24 @@ class Cve(proto.Message): proto.BOOL, number=4, ) + impact: RiskRating = proto.Field( + proto.ENUM, + number=5, + enum=RiskRating, + ) + exploitation_activity: ExploitationActivity = proto.Field( + proto.ENUM, + number=6, + enum=ExploitationActivity, + ) + observed_in_the_wild: bool = proto.Field( + proto.BOOL, + number=7, + ) + zero_day: bool = proto.Field( + proto.BOOL, + number=8, + ) class Reference(proto.Message): @@ -350,4 +468,71 @@ class Impact(proto.Enum): ) +class Package(proto.Message): + r"""Package is a generic definition of a package. + + Attributes: + package_name (str): + The name of the package where the + vulnerability was detected. + cpe_uri (str): + The CPE URI where the vulnerability was + detected. + package_type (str): + Type of package, for example, os, maven, or + go. + package_version (str): + The version of the package. + """ + + package_name: str = proto.Field( + proto.STRING, + number=1, + ) + cpe_uri: str = proto.Field( + proto.STRING, + number=2, + ) + package_type: str = proto.Field( + proto.STRING, + number=3, + ) + package_version: str = proto.Field( + proto.STRING, + number=4, + ) + + +class SecurityBulletin(proto.Message): + r"""SecurityBulletin are notifications of vulnerabilities of + Google products. + + Attributes: + bulletin_id (str): + ID of the bulletin corresponding to the + vulnerability. + submission_time (google.protobuf.timestamp_pb2.Timestamp): + Submission time of this Security Bulletin. + suggested_upgrade_version (str): + This represents a version that the cluster + receiving this notification should be upgraded + to, based on its current version. For example, + 1.15.0 + """ + + bulletin_id: str = proto.Field( + proto.STRING, + number=1, + ) + submission_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + suggested_upgrade_version: str = proto.Field( + proto.STRING, + number=3, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1beta1/gapic_version.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1beta1/gapic_version.py index 484507c567a0..251e3720307c 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1beta1/gapic_version.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.27.0" # {x-release-please-version} +__version__ = "1.28.0" # {x-release-please-version} diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1p1beta1/gapic_version.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1p1beta1/gapic_version.py index 484507c567a0..251e3720307c 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1p1beta1/gapic_version.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1p1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.27.0" # {x-release-please-version} +__version__ = "1.28.0" # {x-release-please-version} diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/__init__.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/__init__.py new file mode 100644 index 000000000000..c64249b8bcfa --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/__init__.py @@ -0,0 +1,224 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 google.cloud.securitycenter_v2 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.security_center import SecurityCenterAsyncClient, SecurityCenterClient +from .types.access import Access, Geolocation, ServiceAccountDelegationInfo +from .types.application import Application +from .types.attack_exposure import AttackExposure +from .types.attack_path import AttackPath +from .types.backup_disaster_recovery import BackupDisasterRecovery +from .types.bigquery_export import BigQueryExport +from .types.cloud_dlp_data_profile import CloudDlpDataProfile +from .types.cloud_dlp_inspection import CloudDlpInspection +from .types.compliance import Compliance +from .types.connection import Connection +from .types.contact_details import Contact, ContactDetails +from .types.container import Container +from .types.database import Database +from .types.exfiltration import ExfilResource, Exfiltration +from .types.external_system import ExternalSystem +from .types.file import File +from .types.finding import Finding +from .types.iam_binding import IamBinding +from .types.indicator import Indicator +from .types.kernel_rootkit import KernelRootkit +from .types.kubernetes import Kubernetes +from .types.label import Label +from .types.load_balancer import LoadBalancer +from .types.log_entry import CloudLoggingEntry, LogEntry +from .types.mitre_attack import MitreAttack +from .types.mute_config import MuteConfig +from .types.notification_config import NotificationConfig +from .types.notification_message import NotificationMessage +from .types.org_policy import OrgPolicy +from .types.process import EnvironmentVariable, Process +from .types.resource import Resource +from .types.resource_value_config import ResourceValue, ResourceValueConfig +from .types.security_marks import SecurityMarks +from .types.security_posture import SecurityPosture +from .types.securitycenter_service import ( + BatchCreateResourceValueConfigsRequest, + BatchCreateResourceValueConfigsResponse, + BulkMuteFindingsRequest, + BulkMuteFindingsResponse, + CreateBigQueryExportRequest, + CreateFindingRequest, + CreateMuteConfigRequest, + CreateNotificationConfigRequest, + CreateResourceValueConfigRequest, + CreateSourceRequest, + DeleteBigQueryExportRequest, + DeleteMuteConfigRequest, + DeleteNotificationConfigRequest, + DeleteResourceValueConfigRequest, + GetBigQueryExportRequest, + GetMuteConfigRequest, + GetNotificationConfigRequest, + GetResourceValueConfigRequest, + GetSimulationRequest, + GetSourceRequest, + GetValuedResourceRequest, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListAttackPathsRequest, + ListAttackPathsResponse, + ListBigQueryExportsRequest, + ListBigQueryExportsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListMuteConfigsRequest, + ListMuteConfigsResponse, + ListNotificationConfigsRequest, + ListNotificationConfigsResponse, + ListResourceValueConfigsRequest, + ListResourceValueConfigsResponse, + ListSourcesRequest, + ListSourcesResponse, + ListValuedResourcesRequest, + ListValuedResourcesResponse, + SetFindingStateRequest, + SetMuteRequest, + UpdateBigQueryExportRequest, + UpdateExternalSystemRequest, + UpdateFindingRequest, + UpdateMuteConfigRequest, + UpdateNotificationConfigRequest, + UpdateResourceValueConfigRequest, + UpdateSecurityMarksRequest, + UpdateSourceRequest, +) +from .types.simulation import Simulation +from .types.source import Source +from .types.valued_resource import ResourceValueConfigMetadata, ValuedResource +from .types.vulnerability import ( + Cve, + Cvssv3, + Package, + Reference, + SecurityBulletin, + Vulnerability, +) + +__all__ = ( + "SecurityCenterAsyncClient", + "Access", + "Application", + "AttackExposure", + "AttackPath", + "BackupDisasterRecovery", + "BatchCreateResourceValueConfigsRequest", + "BatchCreateResourceValueConfigsResponse", + "BigQueryExport", + "BulkMuteFindingsRequest", + "BulkMuteFindingsResponse", + "CloudDlpDataProfile", + "CloudDlpInspection", + "CloudLoggingEntry", + "Compliance", + "Connection", + "Contact", + "ContactDetails", + "Container", + "CreateBigQueryExportRequest", + "CreateFindingRequest", + "CreateMuteConfigRequest", + "CreateNotificationConfigRequest", + "CreateResourceValueConfigRequest", + "CreateSourceRequest", + "Cve", + "Cvssv3", + "Database", + "DeleteBigQueryExportRequest", + "DeleteMuteConfigRequest", + "DeleteNotificationConfigRequest", + "DeleteResourceValueConfigRequest", + "EnvironmentVariable", + "ExfilResource", + "Exfiltration", + "ExternalSystem", + "File", + "Finding", + "Geolocation", + "GetBigQueryExportRequest", + "GetMuteConfigRequest", + "GetNotificationConfigRequest", + "GetResourceValueConfigRequest", + "GetSimulationRequest", + "GetSourceRequest", + "GetValuedResourceRequest", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "IamBinding", + "Indicator", + "KernelRootkit", + "Kubernetes", + "Label", + "ListAttackPathsRequest", + "ListAttackPathsResponse", + "ListBigQueryExportsRequest", + "ListBigQueryExportsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "ListMuteConfigsRequest", + "ListMuteConfigsResponse", + "ListNotificationConfigsRequest", + "ListNotificationConfigsResponse", + "ListResourceValueConfigsRequest", + "ListResourceValueConfigsResponse", + "ListSourcesRequest", + "ListSourcesResponse", + "ListValuedResourcesRequest", + "ListValuedResourcesResponse", + "LoadBalancer", + "LogEntry", + "MitreAttack", + "MuteConfig", + "NotificationConfig", + "NotificationMessage", + "OrgPolicy", + "Package", + "Process", + "Reference", + "Resource", + "ResourceValue", + "ResourceValueConfig", + "ResourceValueConfigMetadata", + "SecurityBulletin", + "SecurityCenterClient", + "SecurityMarks", + "SecurityPosture", + "ServiceAccountDelegationInfo", + "SetFindingStateRequest", + "SetMuteRequest", + "Simulation", + "Source", + "UpdateBigQueryExportRequest", + "UpdateExternalSystemRequest", + "UpdateFindingRequest", + "UpdateMuteConfigRequest", + "UpdateNotificationConfigRequest", + "UpdateResourceValueConfigRequest", + "UpdateSecurityMarksRequest", + "UpdateSourceRequest", + "ValuedResource", + "Vulnerability", +) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/gapic_metadata.json b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/gapic_metadata.json new file mode 100644 index 000000000000..517d51c03f32 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/gapic_metadata.json @@ -0,0 +1,628 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.securitycenter_v2", + "protoPackage": "google.cloud.securitycenter.v2", + "schema": "1.0", + "services": { + "SecurityCenter": { + "clients": { + "grpc": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "BatchCreateResourceValueConfigs": { + "methods": [ + "batch_create_resource_value_configs" + ] + }, + "BulkMuteFindings": { + "methods": [ + "bulk_mute_findings" + ] + }, + "CreateBigQueryExport": { + "methods": [ + "create_big_query_export" + ] + }, + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateMuteConfig": { + "methods": [ + "create_mute_config" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteBigQueryExport": { + "methods": [ + "delete_big_query_export" + ] + }, + "DeleteMuteConfig": { + "methods": [ + "delete_mute_config" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "DeleteResourceValueConfig": { + "methods": [ + "delete_resource_value_config" + ] + }, + "GetBigQueryExport": { + "methods": [ + "get_big_query_export" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetMuteConfig": { + "methods": [ + "get_mute_config" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetResourceValueConfig": { + "methods": [ + "get_resource_value_config" + ] + }, + "GetSimulation": { + "methods": [ + "get_simulation" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GetValuedResource": { + "methods": [ + "get_valued_resource" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAttackPaths": { + "methods": [ + "list_attack_paths" + ] + }, + "ListBigQueryExports": { + "methods": [ + "list_big_query_exports" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListMuteConfigs": { + "methods": [ + "list_mute_configs" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListResourceValueConfigs": { + "methods": [ + "list_resource_value_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "ListValuedResources": { + "methods": [ + "list_valued_resources" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetMute": { + "methods": [ + "set_mute" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBigQueryExport": { + "methods": [ + "update_big_query_export" + ] + }, + "UpdateExternalSystem": { + "methods": [ + "update_external_system" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateMuteConfig": { + "methods": [ + "update_mute_config" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateResourceValueConfig": { + "methods": [ + "update_resource_value_config" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecurityCenterAsyncClient", + "rpcs": { + "BatchCreateResourceValueConfigs": { + "methods": [ + "batch_create_resource_value_configs" + ] + }, + "BulkMuteFindings": { + "methods": [ + "bulk_mute_findings" + ] + }, + "CreateBigQueryExport": { + "methods": [ + "create_big_query_export" + ] + }, + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateMuteConfig": { + "methods": [ + "create_mute_config" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteBigQueryExport": { + "methods": [ + "delete_big_query_export" + ] + }, + "DeleteMuteConfig": { + "methods": [ + "delete_mute_config" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "DeleteResourceValueConfig": { + "methods": [ + "delete_resource_value_config" + ] + }, + "GetBigQueryExport": { + "methods": [ + "get_big_query_export" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetMuteConfig": { + "methods": [ + "get_mute_config" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetResourceValueConfig": { + "methods": [ + "get_resource_value_config" + ] + }, + "GetSimulation": { + "methods": [ + "get_simulation" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GetValuedResource": { + "methods": [ + "get_valued_resource" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAttackPaths": { + "methods": [ + "list_attack_paths" + ] + }, + "ListBigQueryExports": { + "methods": [ + "list_big_query_exports" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListMuteConfigs": { + "methods": [ + "list_mute_configs" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListResourceValueConfigs": { + "methods": [ + "list_resource_value_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "ListValuedResources": { + "methods": [ + "list_valued_resources" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetMute": { + "methods": [ + "set_mute" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBigQueryExport": { + "methods": [ + "update_big_query_export" + ] + }, + "UpdateExternalSystem": { + "methods": [ + "update_external_system" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateMuteConfig": { + "methods": [ + "update_mute_config" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateResourceValueConfig": { + "methods": [ + "update_resource_value_config" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "rest": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "BatchCreateResourceValueConfigs": { + "methods": [ + "batch_create_resource_value_configs" + ] + }, + "BulkMuteFindings": { + "methods": [ + "bulk_mute_findings" + ] + }, + "CreateBigQueryExport": { + "methods": [ + "create_big_query_export" + ] + }, + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateMuteConfig": { + "methods": [ + "create_mute_config" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteBigQueryExport": { + "methods": [ + "delete_big_query_export" + ] + }, + "DeleteMuteConfig": { + "methods": [ + "delete_mute_config" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "DeleteResourceValueConfig": { + "methods": [ + "delete_resource_value_config" + ] + }, + "GetBigQueryExport": { + "methods": [ + "get_big_query_export" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetMuteConfig": { + "methods": [ + "get_mute_config" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetResourceValueConfig": { + "methods": [ + "get_resource_value_config" + ] + }, + "GetSimulation": { + "methods": [ + "get_simulation" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GetValuedResource": { + "methods": [ + "get_valued_resource" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAttackPaths": { + "methods": [ + "list_attack_paths" + ] + }, + "ListBigQueryExports": { + "methods": [ + "list_big_query_exports" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListMuteConfigs": { + "methods": [ + "list_mute_configs" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListResourceValueConfigs": { + "methods": [ + "list_resource_value_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "ListValuedResources": { + "methods": [ + "list_valued_resources" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SetMute": { + "methods": [ + "set_mute" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBigQueryExport": { + "methods": [ + "update_big_query_export" + ] + }, + "UpdateExternalSystem": { + "methods": [ + "update_external_system" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateMuteConfig": { + "methods": [ + "update_mute_config" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateResourceValueConfig": { + "methods": [ + "update_resource_value_config" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + } + } + } + } +} diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/gapic_version.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/py.typed b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/py.typed new file mode 100644 index 000000000000..23a44fc7e4ca --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/__init__.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/__init__.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/__init__.py new file mode 100644 index 000000000000..2ca1ad835af4 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .async_client import SecurityCenterAsyncClient +from .client import SecurityCenterClient + +__all__ = ( + "SecurityCenterClient", + "SecurityCenterAsyncClient", +) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/async_client.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/async_client.py new file mode 100644 index 000000000000..f52aaf06f809 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/async_client.py @@ -0,0 +1,5667 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.securitycenter_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.securitycenter_v2.services.security_center import pagers +from google.cloud.securitycenter_v2.types import ( + access, + application, + attack_exposure, + attack_path, + backup_disaster_recovery, + bigquery_export, + cloud_dlp_data_profile, + cloud_dlp_inspection, + compliance, + connection, + container, + database, + exfiltration, +) +from google.cloud.securitycenter_v2.types import ( + iam_binding, + indicator, + kernel_rootkit, + kubernetes, + load_balancer, + log_entry, + mitre_attack, +) +from google.cloud.securitycenter_v2.types import ( + security_posture, + securitycenter_service, + simulation, +) +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v2.types import ( + resource_value_config as gcs_resource_value_config, +) +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import file +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import org_policy, process +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import security_marks +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource, vulnerability + +from .client import SecurityCenterClient +from .transports.base import DEFAULT_CLIENT_INFO, SecurityCenterTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport + + +class SecurityCenterAsyncClient: + """V2 APIs for Security Center service.""" + + _client: SecurityCenterClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SecurityCenterClient._DEFAULT_UNIVERSE + + attack_path_path = staticmethod(SecurityCenterClient.attack_path_path) + parse_attack_path_path = staticmethod(SecurityCenterClient.parse_attack_path_path) + big_query_export_path = staticmethod(SecurityCenterClient.big_query_export_path) + parse_big_query_export_path = staticmethod( + SecurityCenterClient.parse_big_query_export_path + ) + dlp_job_path = staticmethod(SecurityCenterClient.dlp_job_path) + parse_dlp_job_path = staticmethod(SecurityCenterClient.parse_dlp_job_path) + external_system_path = staticmethod(SecurityCenterClient.external_system_path) + parse_external_system_path = staticmethod( + SecurityCenterClient.parse_external_system_path + ) + finding_path = staticmethod(SecurityCenterClient.finding_path) + parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) + mute_config_path = staticmethod(SecurityCenterClient.mute_config_path) + parse_mute_config_path = staticmethod(SecurityCenterClient.parse_mute_config_path) + notification_config_path = staticmethod( + SecurityCenterClient.notification_config_path + ) + parse_notification_config_path = staticmethod( + SecurityCenterClient.parse_notification_config_path + ) + policy_path = staticmethod(SecurityCenterClient.policy_path) + parse_policy_path = staticmethod(SecurityCenterClient.parse_policy_path) + resource_value_config_path = staticmethod( + SecurityCenterClient.resource_value_config_path + ) + parse_resource_value_config_path = staticmethod( + SecurityCenterClient.parse_resource_value_config_path + ) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + parse_security_marks_path = staticmethod( + SecurityCenterClient.parse_security_marks_path + ) + simulation_path = staticmethod(SecurityCenterClient.simulation_path) + parse_simulation_path = staticmethod(SecurityCenterClient.parse_simulation_path) + source_path = staticmethod(SecurityCenterClient.source_path) + parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) + table_data_profile_path = staticmethod(SecurityCenterClient.table_data_profile_path) + parse_table_data_profile_path = staticmethod( + SecurityCenterClient.parse_table_data_profile_path + ) + topic_path = staticmethod(SecurityCenterClient.topic_path) + parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) + valued_resource_path = staticmethod(SecurityCenterClient.valued_resource_path) + parse_valued_resource_path = staticmethod( + SecurityCenterClient.parse_valued_resource_path + ) + common_billing_account_path = staticmethod( + SecurityCenterClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SecurityCenterClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) + parse_common_folder_path = staticmethod( + SecurityCenterClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + SecurityCenterClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + SecurityCenterClient.parse_common_organization_path + ) + common_project_path = staticmethod(SecurityCenterClient.common_project_path) + parse_common_project_path = staticmethod( + SecurityCenterClient.parse_common_project_path + ) + common_location_path = staticmethod(SecurityCenterClient.common_location_path) + parse_common_location_path = staticmethod( + SecurityCenterClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SecurityCenterClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial( + type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient) + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.SecurityCenterTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SecurityCenterClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def batch_create_resource_value_configs( + self, + request: Optional[ + Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + requests: Optional[ + MutableSequence[securitycenter_service.CreateResourceValueConfigRequest] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + r"""Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + .. 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 securitycenter_v2 + + async def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + requests = securitycenter_v2.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = await client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest, dict]]): + The request object. Request message to create multiple + resource value configs + parent (:class:`str`): + Required. Resource name of the new + ResourceValueConfig's parent. The parent + field in the + CreateResourceValueConfigRequest + messages must either be empty or match + this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (:class:`MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]`): + Required. The resource value configs + to be created. + + This corresponds to the ``requests`` 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.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse: + Response message for + BatchCreateResourceValueConfigs + + """ + # 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, requests]) + 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." + ) + + request = securitycenter_service.BatchCreateResourceValueConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests: + request.requests.extend(requests) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_create_resource_value_configs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 bulk_mute_findings( + self, + request: Optional[ + Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), + ) -> operation_async.AsyncOperation: + r"""Kicks off an LRO to bulk mute findings for a parent + based on a filter. If no location is specified, findings + are muted in global. The parent can be either an + organization, folder, or project. The findings matched + by the filter will be muted after the LRO is done. + + .. 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 securitycenter_v2 + + async def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest, dict]]): + The request object. Request message for bulk findings + update. + Note: + + 1. If multiple bulk update requests + match the same resource, the order + in which they get executed is not + defined. + 2. Once a bulk operation is started, + there is no way to stop it. + parent (:class:`str`): + Required. The parent, at which bulk action needs to be + applied. If no location is specified, findings are + updated in global. The following list shows some + examples: + + - ``organizations/[organization_id]`` + - ``organizations/[organization_id]/locations/[location_id]`` + - ``folders/[folder_id]`` + - ``folders/[folder_id]/locations/[location_id]`` + - ``projects/[project_id]`` + - ``projects/[project_id]/locations/[location_id]`` + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v2.types.BulkMuteFindingsResponse` + The response to a BulkMute request. Contains the LRO + information. + + """ + # 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." + ) + + request = securitycenter_service.BulkMuteFindingsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.bulk_mute_findings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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, + securitycenter_service.BulkMuteFindingsResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + async def create_big_query_export( + self, + request: Optional[ + Union[securitycenter_service.CreateBigQueryExportRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + big_query_export_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Creates a BigQuery export. + + .. 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 securitycenter_v2 + + async def sample_create_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = await client.create_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest, dict]]): + The request object. Request message for creating a + BigQuery export. + parent (:class:`str`): + Required. The name of the parent resource of the new + BigQuery export. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export (:class:`google.cloud.securitycenter_v2.types.BigQueryExport`): + Required. The BigQuery export being + created. + + This corresponds to the ``big_query_export`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``big_query_export_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.cloud.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # 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, big_query_export, big_query_export_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." + ) + + request = securitycenter_service.CreateBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if big_query_export is not None: + request.big_query_export = big_query_export + if big_query_export_id is not None: + request.big_query_export_id = big_query_export_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_big_query_export, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 create_finding( + self, + request: Optional[ + Union[securitycenter_service.CreateFindingRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + finding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding in a location. The corresponding + source must exist for finding creation to succeed. + + .. 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 securitycenter_v2 + + async def sample_create_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.CreateFindingRequest, dict]]): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. The + following list shows some examples of the format: + + ``organizations/[organization_id]/sources/[source_id]`` + + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`google.cloud.securitycenter_v2.types.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_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.cloud.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # 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, finding, finding_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." + ) + + request = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding is not None: + request.finding = finding + if finding_id is not None: + request.finding_id = finding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_finding, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 create_mute_config( + self, + request: Optional[ + Union[securitycenter_service.CreateMuteConfigRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + mute_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Creates a mute config. + + .. 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 securitycenter_v2 + + async def sample_create_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "STATIC" + + request = securitycenter_v2.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = await client.create_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.CreateMuteConfigRequest, dict]]): + The request object. Request message for creating a mute + config. + parent (:class:`str`): + Required. Resource name of the new mute configs's + parent. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config (:class:`google.cloud.securitycenter_v2.types.MuteConfig`): + Required. The mute config being + created. + + This corresponds to the ``mute_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``mute_config_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.cloud.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # 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, mute_config, mute_config_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." + ) + + request = securitycenter_service.CreateMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if mute_config is not None: + request.mute_config = mute_config + if mute_config_id is not None: + request.mute_config_id = mute_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_mute_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 create_notification_config( + self, + request: Optional[ + Union[securitycenter_service.CreateNotificationConfigRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + notification_config: Optional[ + gcs_notification_config.NotificationConfig + ] = None, + config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + .. 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 securitycenter_v2 + + async def sample_create_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = await client.create_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest, dict]]): + The request object. Request message for creating a + notification config. + parent (:class:`str`): + Required. Resource name of the new notification config's + parent. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (:class:`google.cloud.securitycenter_v2.types.NotificationConfig`): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (:class:`str`): + Required. + Unique identifier provided by the client + within the parent scope. It must be + between 1 and 128 characters and contain + alphanumeric characters, underscores, or + hyphens only. + + This corresponds to the ``config_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.cloud.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # 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, notification_config, config_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." + ) + + request = securitycenter_service.CreateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if notification_config is not None: + request.notification_config = notification_config + if config_id is not None: + request.config_id = config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_notification_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 create_source( + self, + request: Optional[ + Union[securitycenter_service.CreateSourceRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a source. + + .. 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 securitycenter_v2 + + async def sample_create_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.CreateSourceRequest, dict]]): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`google.cloud.securitycenter_v2.types.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``source`` 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.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # 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, source]) + 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." + ) + + request = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_source, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 delete_big_query_export( + self, + request: Optional[ + Union[securitycenter_service.DeleteBigQueryExportRequest, 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]] = (), + ) -> None: + r"""Deletes an existing BigQuery export. + + .. 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 securitycenter_v2 + + async def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + await client.delete_big_query_export(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest, dict]]): + The request object. Request message for deleting a + BigQuery export. + name (:class:`str`): + Required. The name of the BigQuery export to delete. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}/locations/{location}/bigQueryExports/{export_id}`` + + 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. + """ + # 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." + ) + + request = securitycenter_service.DeleteBigQueryExportRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_big_query_export, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def delete_mute_config( + self, + request: Optional[ + Union[securitycenter_service.DeleteMuteConfigRequest, 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]] = (), + ) -> None: + r"""Deletes an existing mute config. If no location is + specified, default is global. + + .. 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 securitycenter_v2 + + async def sample_delete_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_mute_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest, dict]]): + The request object. Request message for deleting a mute + config. If no location is specified, + default is global. + name (:class:`str`): + Required. Name of the mute config to delete. The + following list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_id}`` + + 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. + """ + # 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." + ) + + request = securitycenter_service.DeleteMuteConfigRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_mute_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def delete_notification_config( + self, + request: Optional[ + Union[securitycenter_service.DeleteNotificationConfigRequest, 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]] = (), + ) -> None: + r"""Deletes a notification config. + + .. 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 securitycenter_v2 + + async def sample_delete_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_notification_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest, dict]]): + The request object. Request message for deleting a + notification config. + name (:class:`str`): + Required. Name of the notification config to delete. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]notificationConfigs/[config_id]`` + + 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. + """ + # 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." + ) + + request = securitycenter_service.DeleteNotificationConfigRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_notification_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def delete_resource_value_config( + self, + request: Optional[ + Union[securitycenter_service.DeleteResourceValueConfigRequest, 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]] = (), + ) -> None: + r"""Deletes a ResourceValueConfig. + + .. 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 securitycenter_v2 + + async def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_resource_value_config(request=request) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest, dict]]): + The request object. Request message to delete resource + value config + name (:class:`str`): + Required. Name of the + ResourceValueConfig to delete + + 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. + """ + # 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." + ) + + request = securitycenter_service.DeleteResourceValueConfigRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_resource_value_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_big_query_export( + self, + request: Optional[ + Union[securitycenter_service.GetBigQueryExportRequest, 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]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Gets a BigQuery export. + + .. 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 securitycenter_v2 + + async def sample_get_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = await client.get_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetBigQueryExportRequest, dict]]): + The request object. Request message for retrieving a + BigQuery export. + name (:class:`str`): + Required. Name of the BigQuery export to retrieve. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}locations/{location}//bigQueryExports/{export_id}`` + + 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.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # 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." + ) + + request = securitycenter_service.GetBigQueryExportRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_big_query_export, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 get_simulation( + self, + request: Optional[ + Union[securitycenter_service.GetSimulationRequest, 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]] = (), + ) -> simulation.Simulation: + r"""Get the simulation by name or the latest simulation + for the given organization. + + .. 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 securitycenter_v2 + + async def sample_get_simulation(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_simulation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetSimulationRequest, dict]]): + The request object. Request message for getting + simulation. Simulation name can include + "latest" to retrieve the latest + simulation For example, + "organizations/123/simulations/latest". + name (:class:`str`): + Required. The organization name or + simulation name of this simulation + Valid format: + + "organizations/{organization}/simulations/latest" + "organizations/{organization}/simulations/{simulation}" + + 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.securitycenter_v2.types.Simulation: + Attack path simulation + """ + # 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." + ) + + request = securitycenter_service.GetSimulationRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_simulation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 get_valued_resource( + self, + request: Optional[ + Union[securitycenter_service.GetValuedResourceRequest, 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]] = (), + ) -> valued_resource.ValuedResource: + r"""Get the valued resource by name + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_get_valued_resource(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_valued_resource(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetValuedResourceRequest, dict]]): + The request object. Request message for getting a valued + resource. + name (:class:`str`): + Required. The name of this valued resource + + Valid format: + "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}" + + 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.securitycenter_v2.types.ValuedResource: + A resource that is determined to have + value to a user's system + + """ + # 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." + ) + + request = securitycenter_service.GetValuedResourceRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_valued_resource, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the access control policy on the specified + Source. + + .. 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 securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` 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.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + 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." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest( + resource=resource, + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # 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 get_mute_config( + self, + request: Optional[ + Union[securitycenter_service.GetMuteConfigRequest, 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]] = (), + ) -> mute_config.MuteConfig: + r"""Gets a mute config. If no location is specified, + default is global. + + .. 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 securitycenter_v2 + + async def sample_get_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetMuteConfigRequest, dict]]): + The request object. Request message for retrieving a mute + config. If no location is specified, + default is global. + name (:class:`str`): + Required. Name of the mute config to retrieve. The + following list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_id}`` + + 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.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # 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." + ) + + request = securitycenter_service.GetMuteConfigRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_mute_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 get_notification_config( + self, + request: Optional[ + Union[securitycenter_service.GetNotificationConfigRequest, 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]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + .. 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 securitycenter_v2 + + async def sample_get_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetNotificationConfigRequest, dict]]): + The request object. Request message for getting a + notification config. + name (:class:`str`): + Required. Name of the notification config to get. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + 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.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # 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." + ) + + request = securitycenter_service.GetNotificationConfigRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_notification_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 get_resource_value_config( + self, + request: Optional[ + Union[securitycenter_service.GetResourceValueConfigRequest, 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]] = (), + ) -> resource_value_config.ResourceValueConfig: + r"""Gets a ResourceValueConfig. + + .. 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 securitycenter_v2 + + async def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest, dict]]): + The request object. Request message to get resource value + config + name (:class:`str`): + Required. Name of the resource value config to retrieve. + Its format is + organizations/{organization}/resourceValueConfigs/{config_id}. + + 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.securitycenter_v2.types.ResourceValueConfig: + A resource value config (RVC) is a + mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # 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." + ) + + request = securitycenter_service.GetResourceValueConfigRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_resource_value_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 get_source( + self, + request: Optional[Union[securitycenter_service.GetSourceRequest, 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]] = (), + ) -> source.Source: + r"""Gets a source. + + .. 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 securitycenter_v2 + + async def sample_get_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GetSourceRequest, dict]]): + The request object. Request message for getting a source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_id]". + + 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.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # 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." + ) + + request = securitycenter_service.GetSourceRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_source, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 group_findings( + self, + request: Optional[ + Union[securitycenter_service.GroupFindingsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsAsyncPager: + r"""Filters an organization or source's findings and groups them by + their specified properties in a location. If no location is + specified, findings are assumed to be in global + + To group across all sources provide a ``-`` as the source id. + The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + - ``/v2/folders/{folder_id}/sources/-/findings`` + - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` + - ``/v2/projects/{project_id}/sources/-/findings`` + - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` + + .. 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 securitycenter_v2 + + async def sample_group_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.GroupFindingsRequest, dict]]): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. If no location + is specified, finding is assumed to be in global. The + following list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To groupBy across all sources provide a source_id of + ``-``. The following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/[location_id]`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-/locations/[location_id]`` + - ``projects/{project_id}/sources/-`` + - ``projects/{project_id}/sources/-/locations/[location_id]`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping. The string value should follow SQL + syntax: comma separated list of fields. For example: + "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + - severity + + This corresponds to the ``group_by`` 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.securitycenter_v2.services.security_center.pagers.GroupFindingsAsyncPager: + Response message for group by + findings. + 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, group_by]) + 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." + ) + + request = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.group_findings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.GroupFindingsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_attack_paths( + self, + request: Optional[ + Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsAsyncPager: + r"""Lists the attack paths for a set of simulation + results or valued resources and filter. + + .. 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 securitycenter_v2 + + async def sample_list_attack_paths(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListAttackPathsRequest, dict]]): + The request object. Request message for listing the + attack paths for a given simulation or + valued resource. + parent (:class:`str`): + Required. Name of parent to list attack paths. + + Valid formats: "organizations/{organization}", + "organizations/{organization}/simulations/{simulation}" + "organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}" + "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}" + + 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.securitycenter_v2.services.security_center.pagers.ListAttackPathsAsyncPager: + Response message for listing the + attack paths for a given simulation or + valued resource. + + 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." + ) + + request = securitycenter_service.ListAttackPathsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_attack_paths, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListAttackPathsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_big_query_exports( + self, + request: Optional[ + Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsAsyncPager: + r"""Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are 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 securitycenter_v2 + + async def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest, dict]]): + The request object. Request message for listing BigQuery + exports at a given scope e.g. + organization, folder or project. + parent (:class:`str`): + Required. The parent, which owns the collection of + BigQuery exports. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + + 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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsAsyncPager: + Response message for listing BigQuery + exports. + 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." + ) + + request = securitycenter_service.ListBigQueryExportsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_big_query_exports, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListBigQueryExportsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_findings( + self, + request: Optional[ + Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsAsyncPager: + r"""Lists an organization or source's findings. + + To list across all sources for a given location provide a ``-`` + as the source id. If no location is specified, finding are + assumed to be in global. The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + .. 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 securitycenter_v2 + + async def sample_list_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListFindingsRequest, dict]]): + The request object. Request message for listing findings. + parent (:class:`str`): + Required. Name of the source the findings belong to. If + no location is specified, the default is global. The + following list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To list across all sources provide a source_id of ``-``. + The following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/{location_id}`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-locations/{location_id}`` + - ``projects/{projects_id}/sources/-`` + - ``projects/{projects_id}/sources/-/locations/{location_id}`` + + 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.securitycenter_v2.services.security_center.pagers.ListFindingsAsyncPager: + Response message for listing + findings. + 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." + ) + + request = securitycenter_service.ListFindingsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_findings, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListFindingsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_mute_configs( + self, + request: Optional[ + Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsAsyncPager: + r"""Lists mute configs. If no location is specified, + default is global. + + .. 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 securitycenter_v2 + + async def sample_list_mute_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListMuteConfigsRequest, dict]]): + The request object. Request message for listing mute + configs at a given scope e.g. + organization, folder or project. If no + location is specified, default is + global. + parent (:class:`str`): + Required. The parent, which owns the collection of mute + configs. Its format is + "organizations/[organization_id]", + "folders/[folder_id]", "projects/[project_id]", + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", + "projects/[project_id]/locations/[location_id]". + + 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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsAsyncPager: + Response message for listing mute + configs. + 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." + ) + + request = securitycenter_service.ListMuteConfigsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_mute_configs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListMuteConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_notification_configs( + self, + request: Optional[ + Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsAsyncPager: + r"""Lists notification configs. + + .. 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 securitycenter_v2 + + async def sample_list_notification_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest, dict]]): + The request object. Request message for listing + notification configs. + parent (:class:`str`): + Required. The name of the parent in which to list the + notification configurations. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + + 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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsAsyncPager: + Response message for listing + notification configs. + 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." + ) + + request = securitycenter_service.ListNotificationConfigsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_notification_configs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListNotificationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_resource_value_configs( + self, + request: Optional[ + Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsAsyncPager: + r"""Lists all ResourceValueConfigs. + + .. 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 securitycenter_v2 + + async def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest, dict]]): + The request object. Request message to list resource + value configs of a parent + parent (:class:`str`): + Required. The parent, which owns the collection of + resource value configs. Its format is + "organizations/[organization_id]" + + 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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsAsyncPager: + Response message to list resource + value configs + 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." + ) + + request = securitycenter_service.ListResourceValueConfigsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_resource_value_configs, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListResourceValueConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sources( + self, + request: Optional[ + Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesAsyncPager: + r"""Lists all sources belonging to an organization. + + .. 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 securitycenter_v2 + + async def sample_list_sources(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListSourcesRequest, dict]]): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id]", + "folders/[folder_id]", or "projects/[project_id]". + + 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.securitycenter_v2.services.security_center.pagers.ListSourcesAsyncPager: + Response message for listing sources. + + 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." + ) + + request = securitycenter_service.ListSourcesRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_sources, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListSourcesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_valued_resources( + self, + request: Optional[ + Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesAsyncPager: + r"""Lists the valued resources for a set of simulation + results and filter. + + .. 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 securitycenter_v2 + + async def sample_list_valued_resources(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.ListValuedResourcesRequest, dict]]): + The request object. Request message for listing the + valued resources for a given simulation. + parent (:class:`str`): + Required. Name of parent to list exposed resources. + + Valid formats: "organizations/{organization}", + "organizations/{organization}/simulations/{simulation}" + "organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}" + + 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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesAsyncPager: + Response message for listing the + valued resources for a given simulation. + 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." + ) + + request = securitycenter_service.ListValuedResourcesRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_valued_resources, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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.ListValuedResourcesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_finding_state( + self, + request: Optional[ + Union[securitycenter_service.SetFindingStateRequest, dict] + ] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. If no location is + specified, finding is assumed to be in global + + .. 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 securitycenter_v2 + + async def sample_set_finding_state(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.SetFindingStateRequest, dict]]): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`google.cloud.securitycenter_v2.types.Finding.State`): + Required. The desired State of the + finding. + + This corresponds to the ``state`` 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.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # 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, state]) + 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." + ) + + request = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_finding_state, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the access control policy on the specified + Source. + + .. 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 securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` 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.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + 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." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest( + resource=resource, + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # 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 set_mute( + self, + request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, + *, + name: Optional[str] = None, + mute: Optional[finding.Finding.Mute] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the mute state of a finding. If no location + is specified, finding is assumed to be in global + + .. 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 securitycenter_v2 + + async def sample_set_mute(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = await client.set_mute(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.SetMuteRequest, dict]]): + The request object. Request message for updating a + finding's mute status. + name (:class:`str`): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute (:class:`google.cloud.securitycenter_v2.types.Finding.Mute`): + Required. The desired state of the + Mute. + + This corresponds to the ``mute`` 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.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # 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, mute]) + 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." + ) + + request = securitycenter_service.SetMuteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if mute is not None: + request.mute = mute + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_mute, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + .. 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 securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` 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.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + 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." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, + permissions=permissions, + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # 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 update_big_query_export( + self, + request: Optional[ + Union[securitycenter_service.UpdateBigQueryExportRequest, dict] + ] = None, + *, + big_query_export: Optional[bigquery_export.BigQueryExport] = 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]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Updates a BigQuery export. + + .. 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 securitycenter_v2 + + async def sample_update_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateBigQueryExportRequest( + ) + + # Make the request + response = await client.update_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest, dict]]): + The request object. Request message for updating a + BigQuery export. + big_query_export (:class:`google.cloud.securitycenter_v2.types.BigQueryExport`): + Required. The BigQuery export being + updated. + + This corresponds to the ``big_query_export`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. + If empty all mutable fields will be + updated. + + 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.cloud.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # 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([big_query_export, 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." + ) + + request = securitycenter_service.UpdateBigQueryExportRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if big_query_export is not None: + request.big_query_export = big_query_export + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_big_query_export, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("big_query_export.name", request.big_query_export.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 update_external_system( + self, + request: Optional[ + Union[securitycenter_service.UpdateExternalSystemRequest, dict] + ] = None, + *, + external_system: Optional[gcs_external_system.ExternalSystem] = 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]] = (), + ) -> gcs_external_system.ExternalSystem: + r"""Updates external system. This is for a given finding. + If no location is specified, finding is assumed to be in + global + + .. 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 securitycenter_v2 + + async def sample_update_external_system(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateExternalSystemRequest( + ) + + # Make the request + response = await client.update_external_system(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest, dict]]): + The request object. Request message for updating a + ExternalSystem resource. + external_system (:class:`google.cloud.securitycenter_v2.types.ExternalSystem`): + Required. The external system + resource to update. + + This corresponds to the ``external_system`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the external system resource. + If empty all mutable fields will be + updated. + + 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.cloud.securitycenter_v2.types.ExternalSystem: + Representation of third party + SIEM/SOAR fields within SCC. + + """ + # 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([external_system, 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." + ) + + request = securitycenter_service.UpdateExternalSystemRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if external_system is not None: + request.external_system = external_system + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_external_system, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("external_system.name", request.external_system.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 update_finding( + self, + request: Optional[ + Union[securitycenter_service.UpdateFindingRequest, dict] + ] = None, + *, + finding: Optional[gcs_finding.Finding] = 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]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. If no location is + specified, finding is assumed to be in global. The + corresponding source must exist for a finding creation + to succeed. + + .. 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 securitycenter_v2 + + async def sample_update_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateFindingRequest, dict]]): + The request object. Request message for updating or + creating a finding. + finding (:class:`google.cloud.securitycenter_v2.types.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a + finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing + source_properties. Individual source_properties can be + added/updated by using "source_properties." in the field + mask. + + 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.cloud.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # 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([finding, 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." + ) + + request = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_finding, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("finding.name", request.finding.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 update_mute_config( + self, + request: Optional[ + Union[securitycenter_service.UpdateMuteConfigRequest, dict] + ] = None, + *, + mute_config: Optional[gcs_mute_config.MuteConfig] = 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]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Updates a mute config. If no location is specified, + default is global. + + .. 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 securitycenter_v2 + + async def sample_update_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "STATIC" + + request = securitycenter_v2.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = await client.update_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest, dict]]): + The request object. Request message for updating a mute + config. + mute_config (:class:`google.cloud.securitycenter_v2.types.MuteConfig`): + Required. The mute config being + updated. + + This corresponds to the ``mute_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. + If empty all mutable fields will be + updated. + + 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.cloud.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # 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([mute_config, 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." + ) + + request = securitycenter_service.UpdateMuteConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if mute_config is not None: + request.mute_config = mute_config + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_mute_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("mute_config.name", request.mute_config.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 update_notification_config( + self, + request: Optional[ + Union[securitycenter_service.UpdateNotificationConfigRequest, dict] + ] = None, + *, + notification_config: Optional[ + gcs_notification_config.NotificationConfig + ] = 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]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + .. 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 securitycenter_v2 + + async def sample_update_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateNotificationConfigRequest( + ) + + # Make the request + response = await client.update_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest, dict]]): + The request object. Request message for updating a + notification config. + notification_config (:class:`google.cloud.securitycenter_v2.types.NotificationConfig`): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the notification config. + If empty all mutable fields will be + updated. + + 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.cloud.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # 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([notification_config, 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." + ) + + request = securitycenter_service.UpdateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_config + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_notification_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("notification_config.name", request.notification_config.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 update_resource_value_config( + self, + request: Optional[ + Union[securitycenter_service.UpdateResourceValueConfigRequest, dict] + ] = None, + *, + resource_value_config: Optional[ + gcs_resource_value_config.ResourceValueConfig + ] = 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]] = (), + ) -> gcs_resource_value_config.ResourceValueConfig: + r"""Updates an existing ResourceValueConfigs with new + rules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + async def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + resource_value_config = securitycenter_v2.ResourceValueConfig() + resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v2.UpdateResourceValueConfigRequest( + resource_value_config=resource_value_config, + ) + + # Make the request + response = await client.update_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest, dict]]): + The request object. Request message to update resource + value config + resource_value_config (:class:`google.cloud.securitycenter_v2.types.ResourceValueConfig`): + Required. The resource value config + being updated. + + This corresponds to the ``resource_value_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. + If empty all mutable fields will be + updated. + + 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.cloud.securitycenter_v2.types.ResourceValueConfig: + A resource value config (RVC) is a + mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # 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([resource_value_config, 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." + ) + + request = securitycenter_service.UpdateResourceValueConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if resource_value_config is not None: + request.resource_value_config = resource_value_config + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_resource_value_config, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource_value_config.name", request.resource_value_config.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 update_security_marks( + self, + request: Optional[ + Union[securitycenter_service.UpdateSecurityMarksRequest, dict] + ] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = 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]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. For Finding Security marks, + if no location is specified, finding is assumed to be in + global. Assets Security Marks can only be accessed + through global endpoint. + + .. 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 securitycenter_v2 + + async def sample_update_security_marks(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest, dict]]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`google.cloud.securitycenter_v2.types.SecurityMarks`): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If + empty or set to "marks", all marks will be replaced. + Individual marks can be updated using + "marks.". + + 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.cloud.securitycenter_v2.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # 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([security_marks, 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." + ) + + request = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_security_marks, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_marks.name", request.security_marks.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 update_source( + self, + request: Optional[ + Union[securitycenter_service.UpdateSourceRequest, dict] + ] = None, + *, + source: Optional[gcs_source.Source] = 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]] = (), + ) -> gcs_source.Source: + r"""Updates a source. + + .. 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 securitycenter_v2 + + async def sample_update_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.securitycenter_v2.types.UpdateSourceRequest, dict]]): + The request object. Request message for updating a + source. + source (:class:`google.cloud.securitycenter_v2.types.Source`): + Required. The source resource to + update. + + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the source resource. + If empty all mutable fields will be + updated. + + 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.cloud.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # 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([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." + ) + + request = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_source, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("source.name", request.source.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_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` 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: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` 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: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "SecurityCenterAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("SecurityCenterAsyncClient",) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/client.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/client.py new file mode 100644 index 000000000000..7b971f7c919e --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/client.py @@ -0,0 +1,6467 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.securitycenter_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.securitycenter_v2.services.security_center import pagers +from google.cloud.securitycenter_v2.types import ( + access, + application, + attack_exposure, + attack_path, + backup_disaster_recovery, + bigquery_export, + cloud_dlp_data_profile, + cloud_dlp_inspection, + compliance, + connection, + container, + database, + exfiltration, +) +from google.cloud.securitycenter_v2.types import ( + iam_binding, + indicator, + kernel_rootkit, + kubernetes, + load_balancer, + log_entry, + mitre_attack, +) +from google.cloud.securitycenter_v2.types import ( + security_posture, + securitycenter_service, + simulation, +) +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v2.types import ( + resource_value_config as gcs_resource_value_config, +) +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import file +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import org_policy, process +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import security_marks +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource, vulnerability + +from .transports.base import DEFAULT_CLIENT_INFO, SecurityCenterTransport +from .transports.grpc import SecurityCenterGrpcTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .transports.rest import SecurityCenterRestTransport + + +class SecurityCenterClientMeta(type): + """Metaclass for the SecurityCenter client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[SecurityCenterTransport]] + _transport_registry["grpc"] = SecurityCenterGrpcTransport + _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + _transport_registry["rest"] = SecurityCenterRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SecurityCenterTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SecurityCenterClient(metaclass=SecurityCenterClientMeta): + """V2 APIs for Security Center service.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "securitycenter.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "securitycenter.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SecurityCenterClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SecurityCenterClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def attack_path_path( + organization: str, + simulation: str, + valued_resource: str, + attack_path: str, + ) -> str: + """Returns a fully-qualified attack_path string.""" + return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format( + organization=organization, + simulation=simulation, + valued_resource=valued_resource, + attack_path=attack_path, + ) + + @staticmethod + def parse_attack_path_path(path: str) -> Dict[str, str]: + """Parses a attack_path path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?P.+?)/attackPaths/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def big_query_export_path( + organization: str, + location: str, + export: str, + ) -> str: + """Returns a fully-qualified big_query_export string.""" + return "organizations/{organization}/locations/{location}/bigQueryExports/{export}".format( + organization=organization, + location=location, + export=export, + ) + + @staticmethod + def parse_big_query_export_path(path: str) -> Dict[str, str]: + """Parses a big_query_export path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/bigQueryExports/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def dlp_job_path( + project: str, + dlp_job: str, + ) -> str: + """Returns a fully-qualified dlp_job string.""" + return "projects/{project}/dlpJobs/{dlp_job}".format( + project=project, + dlp_job=dlp_job, + ) + + @staticmethod + def parse_dlp_job_path(path: str) -> Dict[str, str]: + """Parses a dlp_job path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/dlpJobs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def external_system_path( + organization: str, + source: str, + finding: str, + externalsystem: str, + ) -> str: + """Returns a fully-qualified external_system string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format( + organization=organization, + source=source, + finding=finding, + externalsystem=externalsystem, + ) + + @staticmethod + def parse_external_system_path(path: str) -> Dict[str, str]: + """Parses a external_system path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)/externalSystems/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def finding_path( + organization: str, + source: str, + finding: str, + ) -> str: + """Returns a fully-qualified finding string.""" + return ( + "organizations/{organization}/sources/{source}/findings/{finding}".format( + organization=organization, + source=source, + finding=finding, + ) + ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str, str]: + """Parses a finding path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def mute_config_path( + organization: str, + mute_config: str, + ) -> str: + """Returns a fully-qualified mute_config string.""" + return "organizations/{organization}/muteConfigs/{mute_config}".format( + organization=organization, + mute_config=mute_config, + ) + + @staticmethod + def parse_mute_config_path(path: str) -> Dict[str, str]: + """Parses a mute_config path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/muteConfigs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def notification_config_path( + organization: str, + location: str, + notification_config: str, + ) -> str: + """Returns a fully-qualified notification_config string.""" + return "organizations/{organization}/locations/{location}/notificationConfigs/{notification_config}".format( + organization=organization, + location=location, + notification_config=notification_config, + ) + + @staticmethod + def parse_notification_config_path(path: str) -> Dict[str, str]: + """Parses a notification_config path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/notificationConfigs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def policy_path( + organization: str, + constraint_name: str, + ) -> str: + """Returns a fully-qualified policy string.""" + return "organizations/{organization}/policies/{constraint_name}".format( + organization=organization, + constraint_name=constraint_name, + ) + + @staticmethod + def parse_policy_path(path: str) -> Dict[str, str]: + """Parses a policy path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/policies/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def resource_value_config_path( + organization: str, + resource_value_config: str, + ) -> str: + """Returns a fully-qualified resource_value_config string.""" + return "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format( + organization=organization, + resource_value_config=resource_value_config, + ) + + @staticmethod + def parse_resource_value_config_path(path: str) -> Dict[str, str]: + """Parses a resource_value_config path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/resourceValueConfigs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def security_marks_path( + organization: str, + asset: str, + ) -> str: + """Returns a fully-qualified security_marks string.""" + return "organizations/{organization}/assets/{asset}/securityMarks".format( + organization=organization, + asset=asset, + ) + + @staticmethod + def parse_security_marks_path(path: str) -> Dict[str, str]: + """Parses a security_marks path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def simulation_path( + organization: str, + simulation: str, + ) -> str: + """Returns a fully-qualified simulation string.""" + return "organizations/{organization}/simulations/{simulation}".format( + organization=organization, + simulation=simulation, + ) + + @staticmethod + def parse_simulation_path(path: str) -> Dict[str, str]: + """Parses a simulation path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/simulations/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def source_path( + organization: str, + source: str, + ) -> str: + """Returns a fully-qualified source string.""" + return "organizations/{organization}/sources/{source}".format( + organization=organization, + source=source, + ) + + @staticmethod + def parse_source_path(path: str) -> Dict[str, str]: + """Parses a source path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/sources/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def table_data_profile_path( + project: str, + table_profile: str, + ) -> str: + """Returns a fully-qualified table_data_profile string.""" + return "projects/{project}/tableProfiles/{table_profile}".format( + project=project, + table_profile=table_profile, + ) + + @staticmethod + def parse_table_data_profile_path(path: str) -> Dict[str, str]: + """Parses a table_data_profile path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/tableProfiles/(?P.+?)$", path + ) + 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 valued_resource_path( + organization: str, + simulation: str, + valued_resource: str, + ) -> str: + """Returns a fully-qualified valued_resource string.""" + return "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format( + organization=organization, + simulation=simulation, + valued_resource=valued_resource, + ) + + @staticmethod + def parse_valued_resource_path(path: str) -> Dict[str, str]: + """Parses a valued_resource path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/simulations/(?P.+?)/valuedResources/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = SecurityCenterClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError( + "The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default." + ) + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = ( + self._is_universe_domain_valid + or SecurityCenterClient._compare_universes( + self.universe_domain, self.transport._credentials + ) + ) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SecurityCenterTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, SecurityCenterTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = SecurityCenterClient._read_environment_variables() + self._client_cert_source = SecurityCenterClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = SecurityCenterClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, SecurityCenterTransport) + if transport_provided: + # transport is a SecurityCenterTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(SecurityCenterTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or SecurityCenterClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + Transport = type(self).get_transport_class(cast(str, transport)) + self._transport = Transport( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def batch_create_resource_value_configs( + self, + request: Optional[ + Union[securitycenter_service.BatchCreateResourceValueConfigsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + requests: Optional[ + MutableSequence[securitycenter_service.CreateResourceValueConfigRequest] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + r"""Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + .. 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 securitycenter_v2 + + def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + requests = securitycenter_v2.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest, dict]): + The request object. Request message to create multiple + resource value configs + parent (str): + Required. Resource name of the new + ResourceValueConfig's parent. The parent + field in the + CreateResourceValueConfigRequest + messages must either be empty or match + this field. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + requests (MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]): + Required. The resource value configs + to be created. + + This corresponds to the ``requests`` 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.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse: + Response message for + BatchCreateResourceValueConfigs + + """ + # 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, requests]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.BatchCreateResourceValueConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.BatchCreateResourceValueConfigsRequest + ): + request = securitycenter_service.BatchCreateResourceValueConfigsRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_create_resource_value_configs + ] + + # 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 bulk_mute_findings( + self, + request: Optional[ + Union[securitycenter_service.BulkMuteFindingsRequest, 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]] = (), + ) -> operation.Operation: + r"""Kicks off an LRO to bulk mute findings for a parent + based on a filter. If no location is specified, findings + are muted in global. The parent can be either an + organization, folder, or project. The findings matched + by the filter will be muted after the LRO is done. + + .. 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 securitycenter_v2 + + def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest, dict]): + The request object. Request message for bulk findings + update. + Note: + + 1. If multiple bulk update requests + match the same resource, the order + in which they get executed is not + defined. + 2. Once a bulk operation is started, + there is no way to stop it. + parent (str): + Required. The parent, at which bulk action needs to be + applied. If no location is specified, findings are + updated in global. The following list shows some + examples: + + - ``organizations/[organization_id]`` + - ``organizations/[organization_id]/locations/[location_id]`` + - ``folders/[folder_id]`` + - ``folders/[folder_id]/locations/[location_id]`` + - ``projects/[project_id]`` + - ``projects/[project_id]/locations/[location_id]`` + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v2.types.BulkMuteFindingsResponse` + The response to a BulkMute request. Contains the LRO + information. + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.BulkMuteFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.BulkMuteFindingsRequest): + request = securitycenter_service.BulkMuteFindingsRequest(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.bulk_mute_findings] + + # 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, + securitycenter_service.BulkMuteFindingsResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + def create_big_query_export( + self, + request: Optional[ + Union[securitycenter_service.CreateBigQueryExportRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + big_query_export: Optional[bigquery_export.BigQueryExport] = None, + big_query_export_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Creates a BigQuery export. + + .. 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 securitycenter_v2 + + def sample_create_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = client.create_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest, dict]): + The request object. Request message for creating a + BigQuery export. + parent (str): + Required. The name of the parent resource of the new + BigQuery export. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): + Required. The BigQuery export being + created. + + This corresponds to the ``big_query_export`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + big_query_export_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``big_query_export_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.cloud.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # 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, big_query_export, big_query_export_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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.CreateBigQueryExportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateBigQueryExportRequest): + request = securitycenter_service.CreateBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if big_query_export is not None: + request.big_query_export = big_query_export + if big_query_export_id is not None: + request.big_query_export_id = big_query_export_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_big_query_export] + + # 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 create_finding( + self, + request: Optional[ + Union[securitycenter_service.CreateFindingRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + finding: Optional[gcs_finding.Finding] = None, + finding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding in a location. The corresponding + source must exist for finding creation to succeed. + + .. 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 securitycenter_v2 + + def sample_create_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.CreateFindingRequest, dict]): + The request object. Request message for creating a + finding. + parent (str): + Required. Resource name of the new finding's parent. The + following list shows some examples of the format: + + ``organizations/[organization_id]/sources/[source_id]`` + + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (google.cloud.securitycenter_v2.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_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.cloud.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # 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, finding, finding_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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.CreateFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding is not None: + request.finding = finding + if finding_id is not None: + request.finding_id = finding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_finding] + + # 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 create_mute_config( + self, + request: Optional[ + Union[securitycenter_service.CreateMuteConfigRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + mute_config: Optional[gcs_mute_config.MuteConfig] = None, + mute_config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Creates a mute config. + + .. 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 securitycenter_v2 + + def sample_create_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "STATIC" + + request = securitycenter_v2.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = client.create_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.CreateMuteConfigRequest, dict]): + The request object. Request message for creating a mute + config. + parent (str): + Required. Resource name of the new mute configs's + parent. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config (google.cloud.securitycenter_v2.types.MuteConfig): + Required. The mute config being + created. + + This corresponds to the ``mute_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute_config_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must consist of only lowercase + letters, numbers, and hyphens, must + start with a letter, must end with + either a letter or a number, and must be + 63 characters or less. + + This corresponds to the ``mute_config_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.cloud.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # 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, mute_config, mute_config_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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.CreateMuteConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateMuteConfigRequest): + request = securitycenter_service.CreateMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if mute_config is not None: + request.mute_config = mute_config + if mute_config_id is not None: + request.mute_config_id = mute_config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_mute_config] + + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)$" + ) + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile( + "^organizations/[^/]+/locations/(?P[^/]+)$" + ) + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile( + "^folders/[^/]+/locations/(?P[^/]+)$" + ) + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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 create_notification_config( + self, + request: Optional[ + Union[securitycenter_service.CreateNotificationConfigRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + notification_config: Optional[ + gcs_notification_config.NotificationConfig + ] = None, + config_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + .. 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 securitycenter_v2 + + def sample_create_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = client.create_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest, dict]): + The request object. Request message for creating a + notification config. + parent (str): + Required. Resource name of the new notification config's + parent. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (str): + Required. + Unique identifier provided by the client + within the parent scope. It must be + between 1 and 128 characters and contain + alphanumeric characters, underscores, or + hyphens only. + + This corresponds to the ``config_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.cloud.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # 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, notification_config, config_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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.CreateNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.CreateNotificationConfigRequest + ): + request = securitycenter_service.CreateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if notification_config is not None: + request.notification_config = notification_config + if config_id is not None: + request.config_id = config_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_notification_config + ] + + # 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 create_source( + self, + request: Optional[ + Union[securitycenter_service.CreateSourceRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + source: Optional[gcs_source.Source] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a source. + + .. 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 securitycenter_v2 + + def sample_create_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.CreateSourceRequest, dict]): + The request object. Request message for creating a + source. + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (google.cloud.securitycenter_v2.types.Source): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # 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, source]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.CreateSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_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, + ) + + # Done; return the response. + return response + + def delete_big_query_export( + self, + request: Optional[ + Union[securitycenter_service.DeleteBigQueryExportRequest, 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]] = (), + ) -> None: + r"""Deletes an existing BigQuery export. + + .. 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 securitycenter_v2 + + def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + client.delete_big_query_export(request=request) + + Args: + request (Union[google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest, dict]): + The request object. Request message for deleting a + BigQuery export. + name (str): + Required. The name of the BigQuery export to delete. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}/locations/{location}/bigQueryExports/{export_id}`` + + 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. + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.DeleteBigQueryExportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.DeleteBigQueryExportRequest): + request = securitycenter_service.DeleteBigQueryExportRequest(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_big_query_export] + + # 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def delete_mute_config( + self, + request: Optional[ + Union[securitycenter_service.DeleteMuteConfigRequest, 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]] = (), + ) -> None: + r"""Deletes an existing mute config. If no location is + specified, default is global. + + .. 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 securitycenter_v2 + + def sample_delete_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_mute_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest, dict]): + The request object. Request message for deleting a mute + config. If no location is specified, + default is global. + name (str): + Required. Name of the mute config to delete. The + following list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_id}`` + + 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. + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.DeleteMuteConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.DeleteMuteConfigRequest): + request = securitycenter_service.DeleteMuteConfigRequest(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_mute_config] + + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile( + "^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile( + "^folders/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def delete_notification_config( + self, + request: Optional[ + Union[securitycenter_service.DeleteNotificationConfigRequest, 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]] = (), + ) -> None: + r"""Deletes a notification config. + + .. 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 securitycenter_v2 + + def sample_delete_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_notification_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest, dict]): + The request object. Request message for deleting a + notification config. + name (str): + Required. Name of the notification config to delete. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]notificationConfigs/[config_id]`` + + 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. + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.DeleteNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.DeleteNotificationConfigRequest + ): + request = securitycenter_service.DeleteNotificationConfigRequest(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_notification_config + ] + + # 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def delete_resource_value_config( + self, + request: Optional[ + Union[securitycenter_service.DeleteResourceValueConfigRequest, 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]] = (), + ) -> None: + r"""Deletes a ResourceValueConfig. + + .. 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 securitycenter_v2 + + def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_resource_value_config(request=request) + + Args: + request (Union[google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest, dict]): + The request object. Request message to delete resource + value config + name (str): + Required. Name of the + ResourceValueConfig to delete + + 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. + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.DeleteResourceValueConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.DeleteResourceValueConfigRequest + ): + request = securitycenter_service.DeleteResourceValueConfigRequest(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_resource_value_config + ] + + # 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_big_query_export( + self, + request: Optional[ + Union[securitycenter_service.GetBigQueryExportRequest, 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]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Gets a BigQuery export. + + .. 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 securitycenter_v2 + + def sample_get_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = client.get_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetBigQueryExportRequest, dict]): + The request object. Request message for retrieving a + BigQuery export. + name (str): + Required. Name of the BigQuery export to retrieve. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}locations/{location}//bigQueryExports/{export_id}`` + + 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.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetBigQueryExportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetBigQueryExportRequest): + request = securitycenter_service.GetBigQueryExportRequest(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_big_query_export] + + # 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 get_simulation( + self, + request: Optional[ + Union[securitycenter_service.GetSimulationRequest, 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]] = (), + ) -> simulation.Simulation: + r"""Get the simulation by name or the latest simulation + for the given organization. + + .. 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 securitycenter_v2 + + def sample_get_simulation(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = client.get_simulation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetSimulationRequest, dict]): + The request object. Request message for getting + simulation. Simulation name can include + "latest" to retrieve the latest + simulation For example, + "organizations/123/simulations/latest". + name (str): + Required. The organization name or + simulation name of this simulation + Valid format: + + "organizations/{organization}/simulations/latest" + "organizations/{organization}/simulations/{simulation}" + + 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.securitycenter_v2.types.Simulation: + Attack path simulation + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetSimulationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetSimulationRequest): + request = securitycenter_service.GetSimulationRequest(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_simulation] + + # 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 get_valued_resource( + self, + request: Optional[ + Union[securitycenter_service.GetValuedResourceRequest, 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]] = (), + ) -> valued_resource.ValuedResource: + r"""Get the valued resource by name + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_get_valued_resource(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_valued_resource(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetValuedResourceRequest, dict]): + The request object. Request message for getting a valued + resource. + name (str): + Required. The name of this valued resource + + Valid format: + "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}" + + 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.securitycenter_v2.types.ValuedResource: + A resource that is determined to have + value to a user's system + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetValuedResourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetValuedResourceRequest): + request = securitycenter_service.GetValuedResourceRequest(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_valued_resource] + + # 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 get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the access control policy on the specified + Source. + + .. 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 securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + 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." + ) + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_mute_config( + self, + request: Optional[ + Union[securitycenter_service.GetMuteConfigRequest, 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]] = (), + ) -> mute_config.MuteConfig: + r"""Gets a mute config. If no location is specified, + default is global. + + .. 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 securitycenter_v2 + + def sample_get_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetMuteConfigRequest, dict]): + The request object. Request message for retrieving a mute + config. If no location is specified, + default is global. + name (str): + Required. Name of the mute config to retrieve. The + following list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_id}`` + + 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.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetMuteConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetMuteConfigRequest): + request = securitycenter_service.GetMuteConfigRequest(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_mute_config] + + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile( + "^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile( + "^folders/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$" + ) + regex_match = routing_param_regex.match(request.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_notification_config( + self, + request: Optional[ + Union[securitycenter_service.GetNotificationConfigRequest, 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]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + .. 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 securitycenter_v2 + + def sample_get_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetNotificationConfigRequest, dict]): + The request object. Request message for getting a + notification config. + name (str): + Required. Name of the notification config to get. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + 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.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(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_notification_config] + + # 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 get_resource_value_config( + self, + request: Optional[ + Union[securitycenter_service.GetResourceValueConfigRequest, 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]] = (), + ) -> resource_value_config.ResourceValueConfig: + r"""Gets a ResourceValueConfig. + + .. 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 securitycenter_v2 + + def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest, dict]): + The request object. Request message to get resource value + config + name (str): + Required. Name of the resource value config to retrieve. + Its format is + organizations/{organization}/resourceValueConfigs/{config_id}. + + 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.securitycenter_v2.types.ResourceValueConfig: + A resource value config (RVC) is a + mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetResourceValueConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.GetResourceValueConfigRequest + ): + request = securitycenter_service.GetResourceValueConfigRequest(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_resource_value_config + ] + + # 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 get_source( + self, + request: Optional[Union[securitycenter_service.GetSourceRequest, 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]] = (), + ) -> source.Source: + r"""Gets a source. + + .. 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 securitycenter_v2 + + def sample_get_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GetSourceRequest, dict]): + The request object. Request message for getting a source. + name (str): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_id]". + + 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.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(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_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 group_findings( + self, + request: Optional[ + Union[securitycenter_service.GroupFindingsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + group_by: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsPager: + r"""Filters an organization or source's findings and groups them by + their specified properties in a location. If no location is + specified, findings are assumed to be in global + + To group across all sources provide a ``-`` as the source id. + The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + - ``/v2/folders/{folder_id}/sources/-/findings`` + - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` + - ``/v2/projects/{project_id}/sources/-/findings`` + - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` + + .. 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 securitycenter_v2 + + def sample_group_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.GroupFindingsRequest, dict]): + The request object. Request message for grouping by + findings. + parent (str): + Required. Name of the source to groupBy. If no location + is specified, finding is assumed to be in global. The + following list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To groupBy across all sources provide a source_id of + ``-``. The following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/[location_id]`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-/locations/[location_id]`` + - ``projects/{project_id}/sources/-`` + - ``projects/{project_id}/sources/-/locations/[location_id]`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (str): + Required. Expression that defines what assets fields to + use for grouping. The string value should follow SQL + syntax: comma separated list of fields. For example: + "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + - severity + + This corresponds to the ``group_by`` 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.securitycenter_v2.services.security_center.pagers.GroupFindingsPager: + Response message for group by + findings. + 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, group_by]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GroupFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_findings] + + # 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.GroupFindingsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_attack_paths( + self, + request: Optional[ + Union[securitycenter_service.ListAttackPathsRequest, 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.ListAttackPathsPager: + r"""Lists the attack paths for a set of simulation + results or valued resources and filter. + + .. 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 securitycenter_v2 + + def sample_list_attack_paths(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListAttackPathsRequest, dict]): + The request object. Request message for listing the + attack paths for a given simulation or + valued resource. + parent (str): + Required. Name of parent to list attack paths. + + Valid formats: "organizations/{organization}", + "organizations/{organization}/simulations/{simulation}" + "organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}" + "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}" + + 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.securitycenter_v2.services.security_center.pagers.ListAttackPathsPager: + Response message for listing the + attack paths for a given simulation or + valued resource. + + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListAttackPathsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListAttackPathsRequest): + request = securitycenter_service.ListAttackPathsRequest(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_attack_paths] + + # 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.ListAttackPathsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_big_query_exports( + self, + request: Optional[ + Union[securitycenter_service.ListBigQueryExportsRequest, 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.ListBigQueryExportsPager: + r"""Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are 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 securitycenter_v2 + + def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest, dict]): + The request object. Request message for listing BigQuery + exports at a given scope e.g. + organization, folder or project. + parent (str): + Required. The parent, which owns the collection of + BigQuery exports. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + + 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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsPager: + Response message for listing BigQuery + exports. + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListBigQueryExportsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListBigQueryExportsRequest): + request = securitycenter_service.ListBigQueryExportsRequest(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_big_query_exports] + + # 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.ListBigQueryExportsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_findings( + self, + request: Optional[ + Union[securitycenter_service.ListFindingsRequest, 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.ListFindingsPager: + r"""Lists an organization or source's findings. + + To list across all sources for a given location provide a ``-`` + as the source id. If no location is specified, finding are + assumed to be in global. The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + .. 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 securitycenter_v2 + + def sample_list_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListFindingsRequest, dict]): + The request object. Request message for listing findings. + parent (str): + Required. Name of the source the findings belong to. If + no location is specified, the default is global. The + following list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To list across all sources provide a source_id of ``-``. + The following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/{location_id}`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-locations/{location_id}`` + - ``projects/{projects_id}/sources/-`` + - ``projects/{projects_id}/sources/-/locations/{location_id}`` + + 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.securitycenter_v2.services.security_center.pagers.ListFindingsPager: + Response message for listing + findings. + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.ListFindingsRequest(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_findings] + + # 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.ListFindingsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_mute_configs( + self, + request: Optional[ + Union[securitycenter_service.ListMuteConfigsRequest, 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.ListMuteConfigsPager: + r"""Lists mute configs. If no location is specified, + default is global. + + .. 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 securitycenter_v2 + + def sample_list_mute_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListMuteConfigsRequest, dict]): + The request object. Request message for listing mute + configs at a given scope e.g. + organization, folder or project. If no + location is specified, default is + global. + parent (str): + Required. The parent, which owns the collection of mute + configs. Its format is + "organizations/[organization_id]", + "folders/[folder_id]", "projects/[project_id]", + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", + "projects/[project_id]/locations/[location_id]". + + 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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsPager: + Response message for listing mute + configs. + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListMuteConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListMuteConfigsRequest): + request = securitycenter_service.ListMuteConfigsRequest(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_mute_configs] + + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)/muteConfigs$" + ) + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile( + "^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs$" + ) + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile( + "^folders/[^/]+/locations/(?P[^/]+)/muteConfigs$" + ) + regex_match = routing_param_regex.match(request.parent) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # 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.ListMuteConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_notification_configs( + self, + request: Optional[ + Union[securitycenter_service.ListNotificationConfigsRequest, 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.ListNotificationConfigsPager: + r"""Lists notification configs. + + .. 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 securitycenter_v2 + + def sample_list_notification_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest, dict]): + The request object. Request message for listing + notification configs. + parent (str): + Required. The name of the parent in which to list the + notification configurations. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + + 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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsPager: + Response message for listing + notification configs. + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListNotificationConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.ListNotificationConfigsRequest + ): + request = securitycenter_service.ListNotificationConfigsRequest(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_notification_configs + ] + + # 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.ListNotificationConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_resource_value_configs( + self, + request: Optional[ + Union[securitycenter_service.ListResourceValueConfigsRequest, 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.ListResourceValueConfigsPager: + r"""Lists all ResourceValueConfigs. + + .. 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 securitycenter_v2 + + def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest, dict]): + The request object. Request message to list resource + value configs of a parent + parent (str): + Required. The parent, which owns the collection of + resource value configs. Its format is + "organizations/[organization_id]" + + 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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsPager: + Response message to list resource + value configs + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListResourceValueConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.ListResourceValueConfigsRequest + ): + request = securitycenter_service.ListResourceValueConfigsRequest(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_resource_value_configs + ] + + # 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.ListResourceValueConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sources( + self, + request: Optional[ + Union[securitycenter_service.ListSourcesRequest, 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.ListSourcesPager: + r"""Lists all sources belonging to an organization. + + .. 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 securitycenter_v2 + + def sample_list_sources(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListSourcesRequest, dict]): + The request object. Request message for listing sources. + parent (str): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id]", + "folders/[folder_id]", or "projects/[project_id]". + + 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.securitycenter_v2.services.security_center.pagers.ListSourcesPager: + Response message for listing sources. + + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListSourcesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(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_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.ListSourcesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_valued_resources( + self, + request: Optional[ + Union[securitycenter_service.ListValuedResourcesRequest, 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.ListValuedResourcesPager: + r"""Lists the valued resources for a set of simulation + results and filter. + + .. 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 securitycenter_v2 + + def sample_list_valued_resources(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.ListValuedResourcesRequest, dict]): + The request object. Request message for listing the + valued resources for a given simulation. + parent (str): + Required. Name of parent to list exposed resources. + + Valid formats: "organizations/{organization}", + "organizations/{organization}/simulations/{simulation}" + "organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}" + + 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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesPager: + Response message for listing the + valued resources for a given simulation. + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListValuedResourcesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListValuedResourcesRequest): + request = securitycenter_service.ListValuedResourcesRequest(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_valued_resources] + + # 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.ListValuedResourcesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_finding_state( + self, + request: Optional[ + Union[securitycenter_service.SetFindingStateRequest, dict] + ] = None, + *, + name: Optional[str] = None, + state: Optional[finding.Finding.State] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. If no location is + specified, finding is assumed to be in global + + .. 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 securitycenter_v2 + + def sample_set_finding_state(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.SetFindingStateRequest, dict]): + The request object. Request message for updating a + finding's state. + name (str): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (google.cloud.securitycenter_v2.types.Finding.State): + Required. The desired State of the + finding. + + This corresponds to the ``state`` 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.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # 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, state]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.SetFindingStateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_finding_state] + + # 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 set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the access control policy on the specified + Source. + + .. 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 securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + 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." + ) + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_mute( + self, + request: Optional[Union[securitycenter_service.SetMuteRequest, dict]] = None, + *, + name: Optional[str] = None, + mute: Optional[finding.Finding.Mute] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the mute state of a finding. If no location + is specified, finding is assumed to be in global + + .. 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 securitycenter_v2 + + def sample_set_mute(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = client.set_mute(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.SetMuteRequest, dict]): + The request object. Request message for updating a + finding's mute status. + name (str): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mute (google.cloud.securitycenter_v2.types.Finding.Mute): + Required. The desired state of the + Mute. + + This corresponds to the ``mute`` 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.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # 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, mute]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.SetMuteRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.SetMuteRequest): + request = securitycenter_service.SetMuteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if mute is not None: + request.mute = mute + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_mute] + + # 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 test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + .. 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 securitycenter_v2 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` 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.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions 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([resource, permissions]) + 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." + ) + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_big_query_export( + self, + request: Optional[ + Union[securitycenter_service.UpdateBigQueryExportRequest, dict] + ] = None, + *, + big_query_export: Optional[bigquery_export.BigQueryExport] = 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]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Updates a BigQuery export. + + .. 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 securitycenter_v2 + + def sample_update_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateBigQueryExportRequest( + ) + + # Make the request + response = client.update_big_query_export(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest, dict]): + The request object. Request message for updating a + BigQuery export. + big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): + Required. The BigQuery export being + updated. + + This corresponds to the ``big_query_export`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be + updated. + + 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.cloud.securitycenter_v2.types.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + # 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([big_query_export, 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateBigQueryExportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateBigQueryExportRequest): + request = securitycenter_service.UpdateBigQueryExportRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if big_query_export is not None: + request.big_query_export = big_query_export + 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_big_query_export] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("big_query_export.name", request.big_query_export.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 update_external_system( + self, + request: Optional[ + Union[securitycenter_service.UpdateExternalSystemRequest, dict] + ] = None, + *, + external_system: Optional[gcs_external_system.ExternalSystem] = 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]] = (), + ) -> gcs_external_system.ExternalSystem: + r"""Updates external system. This is for a given finding. + If no location is specified, finding is assumed to be in + global + + .. 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 securitycenter_v2 + + def sample_update_external_system(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateExternalSystemRequest( + ) + + # Make the request + response = client.update_external_system(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest, dict]): + The request object. Request message for updating a + ExternalSystem resource. + external_system (google.cloud.securitycenter_v2.types.ExternalSystem): + Required. The external system + resource to update. + + This corresponds to the ``external_system`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the external system resource. + If empty all mutable fields will be + updated. + + 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.cloud.securitycenter_v2.types.ExternalSystem: + Representation of third party + SIEM/SOAR fields within SCC. + + """ + # 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([external_system, 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateExternalSystemRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateExternalSystemRequest): + request = securitycenter_service.UpdateExternalSystemRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if external_system is not None: + request.external_system = external_system + 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_external_system] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("external_system.name", request.external_system.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 update_finding( + self, + request: Optional[ + Union[securitycenter_service.UpdateFindingRequest, dict] + ] = None, + *, + finding: Optional[gcs_finding.Finding] = 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]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. If no location is + specified, finding is assumed to be in global. The + corresponding source must exist for a finding creation + to succeed. + + .. 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 securitycenter_v2 + + def sample_update_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateFindingRequest, dict]): + The request object. Request message for updating or + creating a finding. + finding (google.cloud.securitycenter_v2.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a + finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing + source_properties. Individual source_properties can be + added/updated by using "source_properties." in the field + mask. + + 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.cloud.securitycenter_v2.types.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # 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([finding, 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + 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_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("finding.name", request.finding.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 update_mute_config( + self, + request: Optional[ + Union[securitycenter_service.UpdateMuteConfigRequest, dict] + ] = None, + *, + mute_config: Optional[gcs_mute_config.MuteConfig] = 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]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Updates a mute config. If no location is specified, + default is global. + + .. 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 securitycenter_v2 + + def sample_update_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "STATIC" + + request = securitycenter_v2.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = client.update_mute_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest, dict]): + The request object. Request message for updating a mute + config. + mute_config (google.cloud.securitycenter_v2.types.MuteConfig): + Required. The mute config being + updated. + + This corresponds to the ``mute_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be + updated. + + 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.cloud.securitycenter_v2.types.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + # 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([mute_config, 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateMuteConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateMuteConfigRequest): + request = securitycenter_service.UpdateMuteConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if mute_config is not None: + request.mute_config = mute_config + 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_mute_config] + + header_params = {} + + routing_param_regex = re.compile( + "^projects/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$" + ) + regex_match = routing_param_regex.match(request.mute_config.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile( + "^organizations/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$" + ) + regex_match = routing_param_regex.match(request.mute_config.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + routing_param_regex = re.compile( + "^folders/[^/]+/locations/(?P[^/]+)/muteConfigs/[^/]+$" + ) + regex_match = routing_param_regex.match(request.mute_config.name) + if regex_match and regex_match.group("location"): + header_params["location"] = regex_match.group("location") + + if header_params: + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(header_params), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_notification_config( + self, + request: Optional[ + Union[securitycenter_service.UpdateNotificationConfigRequest, dict] + ] = None, + *, + notification_config: Optional[ + gcs_notification_config.NotificationConfig + ] = 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]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + .. 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 securitycenter_v2 + + def sample_update_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateNotificationConfigRequest( + ) + + # Make the request + response = client.update_notification_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest, dict]): + The request object. Request message for updating a + notification config. + notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the notification config. + If empty all mutable fields will be + updated. + + 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.cloud.securitycenter_v2.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # 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([notification_config, 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.UpdateNotificationConfigRequest + ): + request = securitycenter_service.UpdateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_config + 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_notification_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("notification_config.name", request.notification_config.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 update_resource_value_config( + self, + request: Optional[ + Union[securitycenter_service.UpdateResourceValueConfigRequest, dict] + ] = None, + *, + resource_value_config: Optional[ + gcs_resource_value_config.ResourceValueConfig + ] = 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]] = (), + ) -> gcs_resource_value_config.ResourceValueConfig: + r"""Updates an existing ResourceValueConfigs with new + rules. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import securitycenter_v2 + + def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + resource_value_config = securitycenter_v2.ResourceValueConfig() + resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v2.UpdateResourceValueConfigRequest( + resource_value_config=resource_value_config, + ) + + # Make the request + response = client.update_resource_value_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest, dict]): + The request object. Request message to update resource + value config + resource_value_config (google.cloud.securitycenter_v2.types.ResourceValueConfig): + Required. The resource value config + being updated. + + This corresponds to the ``resource_value_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be + updated. + + 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.cloud.securitycenter_v2.types.ResourceValueConfig: + A resource value config (RVC) is a + mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + # 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([resource_value_config, 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateResourceValueConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.UpdateResourceValueConfigRequest + ): + request = securitycenter_service.UpdateResourceValueConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if resource_value_config is not None: + request.resource_value_config = resource_value_config + 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_resource_value_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource_value_config.name", request.resource_value_config.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 update_security_marks( + self, + request: Optional[ + Union[securitycenter_service.UpdateSecurityMarksRequest, dict] + ] = None, + *, + security_marks: Optional[gcs_security_marks.SecurityMarks] = 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]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. For Finding Security marks, + if no location is specified, finding is assumed to be in + global. Assets Security Marks can only be accessed + through global endpoint. + + .. 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 securitycenter_v2 + + def sample_update_security_marks(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest, dict]): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (google.cloud.securitycenter_v2.types.SecurityMarks): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If + empty or set to "marks", all marks will be replaced. + Individual marks can be updated using + "marks.". + + 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.cloud.securitycenter_v2.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # 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([security_marks, 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateSecurityMarksRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + 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_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_marks.name", request.security_marks.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 update_source( + self, + request: Optional[ + Union[securitycenter_service.UpdateSourceRequest, dict] + ] = None, + *, + source: Optional[gcs_source.Source] = 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]] = (), + ) -> gcs_source.Source: + r"""Updates a source. + + .. 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 securitycenter_v2 + + def sample_update_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.securitycenter_v2.types.UpdateSourceRequest, dict]): + The request object. Request message for updating a + source. + source (google.cloud.securitycenter_v2.types.Source): + Required. The source resource to + update. + + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the source resource. + If empty all mutable fields will be + updated. + + 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.cloud.securitycenter_v2.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # 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([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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = 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_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("source.name", request.source.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 __enter__(self) -> "SecurityCenterClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` 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.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` 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: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("SecurityCenterClient",) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/pagers.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/pagers.py new file mode 100644 index 000000000000..72a28476b4eb --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/pagers.py @@ -0,0 +1,1220 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.securitycenter_v2.types import ( + attack_path, + bigquery_export, + mute_config, + notification_config, + resource_value_config, + securitycenter_service, + source, + valued_resource, +) + + +class GroupFindingsPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` + 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[..., securitycenter_service.GroupFindingsResponse], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v2.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.GroupFindingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.GroupFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[securitycenter_service.GroupFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GroupFindingsAsyncPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.GroupFindingsResponse` + 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[securitycenter_service.GroupFindingsResponse]], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v2.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.GroupFindingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.GroupFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[securitycenter_service.GroupFindingsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAttackPathsPager: + """A pager for iterating through ``list_attack_paths`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``attack_paths`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAttackPaths`` requests and continue to iterate + through the ``attack_paths`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` + 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[..., securitycenter_service.ListAttackPathsResponse], + request: securitycenter_service.ListAttackPathsRequest, + response: securitycenter_service.ListAttackPathsResponse, + *, + 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.securitycenter_v2.types.ListAttackPathsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListAttackPathsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListAttackPathsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[securitycenter_service.ListAttackPathsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[attack_path.AttackPath]: + for page in self.pages: + yield from page.attack_paths + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAttackPathsAsyncPager: + """A pager for iterating through ``list_attack_paths`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``attack_paths`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAttackPaths`` requests and continue to iterate + through the ``attack_paths`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListAttackPathsResponse` + 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[securitycenter_service.ListAttackPathsResponse] + ], + request: securitycenter_service.ListAttackPathsRequest, + response: securitycenter_service.ListAttackPathsResponse, + *, + 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.securitycenter_v2.types.ListAttackPathsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListAttackPathsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListAttackPathsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[securitycenter_service.ListAttackPathsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[attack_path.AttackPath]: + async def async_generator(): + async for page in self.pages: + for response in page.attack_paths: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBigQueryExportsPager: + """A pager for iterating through ``list_big_query_exports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``big_query_exports`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBigQueryExports`` requests and continue to iterate + through the ``big_query_exports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` + 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[..., securitycenter_service.ListBigQueryExportsResponse], + request: securitycenter_service.ListBigQueryExportsRequest, + response: securitycenter_service.ListBigQueryExportsResponse, + *, + 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.securitycenter_v2.types.ListBigQueryExportsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListBigQueryExportsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[securitycenter_service.ListBigQueryExportsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[bigquery_export.BigQueryExport]: + for page in self.pages: + yield from page.big_query_exports + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBigQueryExportsAsyncPager: + """A pager for iterating through ``list_big_query_exports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``big_query_exports`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBigQueryExports`` requests and continue to iterate + through the ``big_query_exports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse` + 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[securitycenter_service.ListBigQueryExportsResponse] + ], + request: securitycenter_service.ListBigQueryExportsRequest, + response: securitycenter_service.ListBigQueryExportsResponse, + *, + 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.securitycenter_v2.types.ListBigQueryExportsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListBigQueryExportsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListBigQueryExportsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[securitycenter_service.ListBigQueryExportsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[bigquery_export.BigQueryExport]: + async def async_generator(): + async for page in self.pages: + for response in page.big_query_exports: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListFindingsPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListFindingsResponse` + 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[..., securitycenter_service.ListFindingsResponse], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.ListFindingsResponse, + *, + 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.securitycenter_v2.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListFindingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[securitycenter_service.ListFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__( + self, + ) -> Iterator[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + for page in self.pages: + yield from page.list_findings_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListFindingsAsyncPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListFindingsResponse` + 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[securitycenter_service.ListFindingsResponse]], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.ListFindingsResponse, + *, + 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.securitycenter_v2.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListFindingsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[securitycenter_service.ListFindingsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterator[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_findings_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMuteConfigsPager: + """A pager for iterating through ``list_mute_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``mute_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMuteConfigs`` requests and continue to iterate + through the ``mute_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` + 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[..., securitycenter_service.ListMuteConfigsResponse], + request: securitycenter_service.ListMuteConfigsRequest, + response: securitycenter_service.ListMuteConfigsResponse, + *, + 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.securitycenter_v2.types.ListMuteConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListMuteConfigsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListMuteConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[securitycenter_service.ListMuteConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[mute_config.MuteConfig]: + for page in self.pages: + yield from page.mute_configs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMuteConfigsAsyncPager: + """A pager for iterating through ``list_mute_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``mute_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMuteConfigs`` requests and continue to iterate + through the ``mute_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListMuteConfigsResponse` + 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[securitycenter_service.ListMuteConfigsResponse] + ], + request: securitycenter_service.ListMuteConfigsRequest, + response: securitycenter_service.ListMuteConfigsResponse, + *, + 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.securitycenter_v2.types.ListMuteConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListMuteConfigsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListMuteConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[securitycenter_service.ListMuteConfigsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[mute_config.MuteConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.mute_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` + 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[..., securitycenter_service.ListNotificationConfigsResponse], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v2.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListNotificationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[securitycenter_service.ListNotificationConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[notification_config.NotificationConfig]: + for page in self.pages: + yield from page.notification_configs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsAsyncPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse` + 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[securitycenter_service.ListNotificationConfigsResponse] + ], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v2.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListNotificationConfigsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListNotificationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[securitycenter_service.ListNotificationConfigsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[notification_config.NotificationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.notification_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListResourceValueConfigsPager: + """A pager for iterating through ``list_resource_value_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``resource_value_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListResourceValueConfigs`` requests and continue to iterate + through the ``resource_value_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` + 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[..., securitycenter_service.ListResourceValueConfigsResponse], + request: securitycenter_service.ListResourceValueConfigsRequest, + response: securitycenter_service.ListResourceValueConfigsResponse, + *, + 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.securitycenter_v2.types.ListResourceValueConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListResourceValueConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[securitycenter_service.ListResourceValueConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resource_value_config.ResourceValueConfig]: + for page in self.pages: + yield from page.resource_value_configs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListResourceValueConfigsAsyncPager: + """A pager for iterating through ``list_resource_value_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``resource_value_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListResourceValueConfigs`` requests and continue to iterate + through the ``resource_value_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse` + 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[securitycenter_service.ListResourceValueConfigsResponse] + ], + request: securitycenter_service.ListResourceValueConfigsRequest, + response: securitycenter_service.ListResourceValueConfigsResponse, + *, + 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.securitycenter_v2.types.ListResourceValueConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListResourceValueConfigsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListResourceValueConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[securitycenter_service.ListResourceValueConfigsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[resource_value_config.ResourceValueConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.resource_value_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSourcesPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` + 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[..., securitycenter_service.ListSourcesResponse], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v2.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListSourcesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListSourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[securitycenter_service.ListSourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[source.Source]: + for page in self.pages: + yield from page.sources + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSourcesAsyncPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListSourcesResponse` + 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[securitycenter_service.ListSourcesResponse]], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v2.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListSourcesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListSourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[securitycenter_service.ListSourcesResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[source.Source]: + async def async_generator(): + async for page in self.pages: + for response in page.sources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListValuedResourcesPager: + """A pager for iterating through ``list_valued_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``valued_resources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListValuedResources`` requests and continue to iterate + through the ``valued_resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` + 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[..., securitycenter_service.ListValuedResourcesResponse], + request: securitycenter_service.ListValuedResourcesRequest, + response: securitycenter_service.ListValuedResourcesResponse, + *, + 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.securitycenter_v2.types.ListValuedResourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListValuedResourcesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListValuedResourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[securitycenter_service.ListValuedResourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[valued_resource.ValuedResource]: + for page in self.pages: + yield from page.valued_resources + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListValuedResourcesAsyncPager: + """A pager for iterating through ``list_valued_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``valued_resources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListValuedResources`` requests and continue to iterate + through the ``valued_resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v2.types.ListValuedResourcesResponse` + 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[securitycenter_service.ListValuedResourcesResponse] + ], + request: securitycenter_service.ListValuedResourcesRequest, + response: securitycenter_service.ListValuedResourcesResponse, + *, + 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.securitycenter_v2.types.ListValuedResourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v2.types.ListValuedResourcesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListValuedResourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[securitycenter_service.ListValuedResourcesResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[valued_resource.ValuedResource]: + async def async_generator(): + async for page in self.pages: + for response in page.valued_resources: + 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-securitycenter/google/cloud/securitycenter_v2/services/security_center/transports/__init__.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/transports/__init__.py new file mode 100644 index 000000000000..441ce35301f9 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport +from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .rest import SecurityCenterRestInterceptor, SecurityCenterRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] +_transport_registry["grpc"] = SecurityCenterGrpcTransport +_transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport +_transport_registry["rest"] = SecurityCenterRestTransport + +__all__ = ( + "SecurityCenterTransport", + "SecurityCenterGrpcTransport", + "SecurityCenterGrpcAsyncIOTransport", + "SecurityCenterRestTransport", + "SecurityCenterRestInterceptor", +) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/transports/base.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/transports/base.py new file mode 100644 index 000000000000..ae3c5c3559e8 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/transports/base.py @@ -0,0 +1,827 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.securitycenter_v2 import gapic_version as package_version +from google.cloud.securitycenter_v2.types import securitycenter_service, simulation +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v2.types import ( + resource_value_config as gcs_resource_value_config, +) +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "securitycenter.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.batch_create_resource_value_configs: gapic_v1.method.wrap_method( + self.batch_create_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.bulk_mute_findings: gapic_v1.method.wrap_method( + self.bulk_mute_findings, + default_timeout=None, + client_info=client_info, + ), + self.create_big_query_export: gapic_v1.method.wrap_method( + self.create_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.create_finding: gapic_v1.method.wrap_method( + self.create_finding, + default_timeout=None, + client_info=client_info, + ), + self.create_mute_config: gapic_v1.method.wrap_method( + self.create_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.create_notification_config: gapic_v1.method.wrap_method( + self.create_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.create_source: gapic_v1.method.wrap_method( + self.create_source, + default_timeout=None, + client_info=client_info, + ), + self.delete_big_query_export: gapic_v1.method.wrap_method( + self.delete_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.delete_mute_config: gapic_v1.method.wrap_method( + self.delete_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_notification_config: gapic_v1.method.wrap_method( + self.delete_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.delete_resource_value_config: gapic_v1.method.wrap_method( + self.delete_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.get_big_query_export: gapic_v1.method.wrap_method( + self.get_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.get_simulation: gapic_v1.method.wrap_method( + self.get_simulation, + default_timeout=None, + client_info=client_info, + ), + self.get_valued_resource: gapic_v1.method.wrap_method( + self.get_valued_resource, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.get_mute_config: gapic_v1.method.wrap_method( + self.get_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.get_notification_config: gapic_v1.method.wrap_method( + self.get_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.get_resource_value_config: gapic_v1.method.wrap_method( + self.get_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.get_source: gapic_v1.method.wrap_method( + self.get_source, + default_timeout=None, + client_info=client_info, + ), + self.group_findings: gapic_v1.method.wrap_method( + self.group_findings, + default_timeout=None, + client_info=client_info, + ), + self.list_attack_paths: gapic_v1.method.wrap_method( + self.list_attack_paths, + default_timeout=None, + client_info=client_info, + ), + self.list_big_query_exports: gapic_v1.method.wrap_method( + self.list_big_query_exports, + default_timeout=None, + client_info=client_info, + ), + self.list_findings: gapic_v1.method.wrap_method( + self.list_findings, + default_timeout=None, + client_info=client_info, + ), + self.list_mute_configs: gapic_v1.method.wrap_method( + self.list_mute_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_notification_configs: gapic_v1.method.wrap_method( + self.list_notification_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_resource_value_configs: gapic_v1.method.wrap_method( + self.list_resource_value_configs, + default_timeout=None, + client_info=client_info, + ), + self.list_sources: gapic_v1.method.wrap_method( + self.list_sources, + default_timeout=None, + client_info=client_info, + ), + self.list_valued_resources: gapic_v1.method.wrap_method( + self.list_valued_resources, + default_timeout=None, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method.wrap_method( + self.set_finding_state, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_mute: gapic_v1.method.wrap_method( + self.set_mute, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.update_big_query_export: gapic_v1.method.wrap_method( + self.update_big_query_export, + default_timeout=None, + client_info=client_info, + ), + self.update_external_system: gapic_v1.method.wrap_method( + self.update_external_system, + default_timeout=None, + client_info=client_info, + ), + self.update_finding: gapic_v1.method.wrap_method( + self.update_finding, + default_timeout=None, + client_info=client_info, + ), + self.update_mute_config: gapic_v1.method.wrap_method( + self.update_mute_config, + default_timeout=None, + client_info=client_info, + ), + self.update_notification_config: gapic_v1.method.wrap_method( + self.update_notification_config, + default_timeout=None, + client_info=client_info, + ), + self.update_resource_value_config: gapic_v1.method.wrap_method( + self.update_resource_value_config, + default_timeout=None, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method.wrap_method( + self.update_security_marks, + default_timeout=None, + client_info=client_info, + ), + self.update_source: gapic_v1.method.wrap_method( + self.update_source, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def batch_create_resource_value_configs( + self, + ) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + Union[ + securitycenter_service.BatchCreateResourceValueConfigsResponse, + Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def bulk_mute_findings( + self, + ) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def create_big_query_export( + self, + ) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + Union[ + bigquery_export.BigQueryExport, Awaitable[bigquery_export.BigQueryExport] + ], + ]: + raise NotImplementedError() + + @property + def create_finding( + self, + ) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Union[gcs_finding.Finding, Awaitable[gcs_finding.Finding]], + ]: + raise NotImplementedError() + + @property + def create_mute_config( + self, + ) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + Union[gcs_mute_config.MuteConfig, Awaitable[gcs_mute_config.MuteConfig]], + ]: + raise NotImplementedError() + + @property + def create_notification_config( + self, + ) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig], + ], + ]: + raise NotImplementedError() + + @property + def create_source( + self, + ) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Union[gcs_source.Source, Awaitable[gcs_source.Source]], + ]: + raise NotImplementedError() + + @property + def delete_big_query_export( + self, + ) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def delete_mute_config( + self, + ) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def delete_notification_config( + self, + ) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def delete_resource_value_config( + self, + ) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def get_big_query_export( + self, + ) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + Union[ + bigquery_export.BigQueryExport, Awaitable[bigquery_export.BigQueryExport] + ], + ]: + raise NotImplementedError() + + @property + def get_simulation( + self, + ) -> Callable[ + [securitycenter_service.GetSimulationRequest], + Union[simulation.Simulation, Awaitable[simulation.Simulation]], + ]: + raise NotImplementedError() + + @property + def get_valued_resource( + self, + ) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + Union[ + valued_resource.ValuedResource, Awaitable[valued_resource.ValuedResource] + ], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_mute_config( + self, + ) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], + Union[mute_config.MuteConfig, Awaitable[mute_config.MuteConfig]], + ]: + raise NotImplementedError() + + @property + def get_notification_config( + self, + ) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Union[ + notification_config.NotificationConfig, + Awaitable[notification_config.NotificationConfig], + ], + ]: + raise NotImplementedError() + + @property + def get_resource_value_config( + self, + ) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + Union[ + resource_value_config.ResourceValueConfig, + Awaitable[resource_value_config.ResourceValueConfig], + ], + ]: + raise NotImplementedError() + + @property + def get_source( + self, + ) -> Callable[ + [securitycenter_service.GetSourceRequest], + Union[source.Source, Awaitable[source.Source]], + ]: + raise NotImplementedError() + + @property + def group_findings( + self, + ) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Union[ + securitycenter_service.GroupFindingsResponse, + Awaitable[securitycenter_service.GroupFindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_attack_paths( + self, + ) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + Union[ + securitycenter_service.ListAttackPathsResponse, + Awaitable[securitycenter_service.ListAttackPathsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_big_query_exports( + self, + ) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + Union[ + securitycenter_service.ListBigQueryExportsResponse, + Awaitable[securitycenter_service.ListBigQueryExportsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_findings( + self, + ) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Union[ + securitycenter_service.ListFindingsResponse, + Awaitable[securitycenter_service.ListFindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_mute_configs( + self, + ) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + Union[ + securitycenter_service.ListMuteConfigsResponse, + Awaitable[securitycenter_service.ListMuteConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_notification_configs( + self, + ) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Union[ + securitycenter_service.ListNotificationConfigsResponse, + Awaitable[securitycenter_service.ListNotificationConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_resource_value_configs( + self, + ) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + Union[ + securitycenter_service.ListResourceValueConfigsResponse, + Awaitable[securitycenter_service.ListResourceValueConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_sources( + self, + ) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Union[ + securitycenter_service.ListSourcesResponse, + Awaitable[securitycenter_service.ListSourcesResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_valued_resources( + self, + ) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + Union[ + securitycenter_service.ListValuedResourcesResponse, + Awaitable[securitycenter_service.ListValuedResourcesResponse], + ], + ]: + raise NotImplementedError() + + @property + def set_finding_state( + self, + ) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Union[finding.Finding, Awaitable[finding.Finding]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def set_mute( + self, + ) -> Callable[ + [securitycenter_service.SetMuteRequest], + Union[finding.Finding, Awaitable[finding.Finding]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_big_query_export( + self, + ) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + Union[ + bigquery_export.BigQueryExport, Awaitable[bigquery_export.BigQueryExport] + ], + ]: + raise NotImplementedError() + + @property + def update_external_system( + self, + ) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + Union[ + gcs_external_system.ExternalSystem, + Awaitable[gcs_external_system.ExternalSystem], + ], + ]: + raise NotImplementedError() + + @property + def update_finding( + self, + ) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Union[gcs_finding.Finding, Awaitable[gcs_finding.Finding]], + ]: + raise NotImplementedError() + + @property + def update_mute_config( + self, + ) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + Union[gcs_mute_config.MuteConfig, Awaitable[gcs_mute_config.MuteConfig]], + ]: + raise NotImplementedError() + + @property + def update_notification_config( + self, + ) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig], + ], + ]: + raise NotImplementedError() + + @property + def update_resource_value_config( + self, + ) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + Union[ + gcs_resource_value_config.ResourceValueConfig, + Awaitable[gcs_resource_value_config.ResourceValueConfig], + ], + ]: + raise NotImplementedError() + + @property + def update_security_marks( + self, + ) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Union[ + gcs_security_marks.SecurityMarks, + Awaitable[gcs_security_marks.SecurityMarks], + ], + ]: + raise NotImplementedError() + + @property + def update_source( + self, + ) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Union[gcs_source.Source, Awaitable[gcs_source.Source]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None,]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("SecurityCenterTransport",) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py new file mode 100644 index 000000000000..05e0d73b7991 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/transports/grpc.py @@ -0,0 +1,1527 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +import grpc # type: ignore + +from google.cloud.securitycenter_v2.types import securitycenter_service, simulation +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v2.types import ( + resource_value_config as gcs_resource_value_config, +) +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource + +from .base import DEFAULT_CLIENT_INFO, SecurityCenterTransport + + +class SecurityCenterGrpcTransport(SecurityCenterTransport): + """gRPC backend transport for SecurityCenter. + + V2 APIs for Security Center service. + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "securitycenter.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.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. + This argument is ignored if ``channel`` is provided. + 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. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "securitycenter.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient(self.grpc_channel) + + # Return the client from cache. + return self._operations_client + + @property + def batch_create_resource_value_configs( + self, + ) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + securitycenter_service.BatchCreateResourceValueConfigsResponse, + ]: + r"""Return a callable for the batch create resource value + configs method over gRPC. + + Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + Returns: + Callable[[~.BatchCreateResourceValueConfigsRequest], + ~.BatchCreateResourceValueConfigsResponse]: + 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 "batch_create_resource_value_configs" not in self._stubs: + self._stubs[ + "batch_create_resource_value_configs" + ] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/BatchCreateResourceValueConfigs", + request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, + ) + return self._stubs["batch_create_resource_value_configs"] + + @property + def bulk_mute_findings( + self, + ) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], operations_pb2.Operation + ]: + r"""Return a callable for the bulk mute findings method over gRPC. + + Kicks off an LRO to bulk mute findings for a parent + based on a filter. If no location is specified, findings + are muted in global. The parent can be either an + organization, folder, or project. The findings matched + by the filter will be muted after the LRO is done. + + Returns: + Callable[[~.BulkMuteFindingsRequest], + ~.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 "bulk_mute_findings" not in self._stubs: + self._stubs["bulk_mute_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/BulkMuteFindings", + request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["bulk_mute_findings"] + + @property + def create_big_query_export( + self, + ) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + bigquery_export.BigQueryExport, + ]: + r"""Return a callable for the create big query export method over gRPC. + + Creates a BigQuery export. + + Returns: + Callable[[~.CreateBigQueryExportRequest], + ~.BigQueryExport]: + 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_big_query_export" not in self._stubs: + self._stubs["create_big_query_export"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/CreateBigQueryExport", + request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs["create_big_query_export"] + + @property + def create_finding( + self, + ) -> Callable[[securitycenter_service.CreateFindingRequest], gcs_finding.Finding]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding in a location. The corresponding + source must exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + ~.Finding]: + 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_finding" not in self._stubs: + self._stubs["create_finding"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/CreateFinding", + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs["create_finding"] + + @property + def create_mute_config( + self, + ) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], gcs_mute_config.MuteConfig + ]: + r"""Return a callable for the create mute config method over gRPC. + + Creates a mute config. + + Returns: + Callable[[~.CreateMuteConfigRequest], + ~.MuteConfig]: + 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_mute_config" not in self._stubs: + self._stubs["create_mute_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/CreateMuteConfig", + request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs["create_mute_config"] + + @property + def create_notification_config( + self, + ) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig, + ]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + ~.NotificationConfig]: + 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_notification_config" not in self._stubs: + self._stubs["create_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/CreateNotificationConfig", + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs["create_notification_config"] + + @property + def create_source( + self, + ) -> Callable[[securitycenter_service.CreateSourceRequest], gcs_source.Source]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + ~.Source]: + 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_source" not in self._stubs: + self._stubs["create_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/CreateSource", + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs["create_source"] + + @property + def delete_big_query_export( + self, + ) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], empty_pb2.Empty + ]: + r"""Return a callable for the delete big query export method over gRPC. + + Deletes an existing BigQuery export. + + Returns: + Callable[[~.DeleteBigQueryExportRequest], + ~.Empty]: + 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_big_query_export" not in self._stubs: + self._stubs["delete_big_query_export"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/DeleteBigQueryExport", + request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_big_query_export"] + + @property + def delete_mute_config( + self, + ) -> Callable[[securitycenter_service.DeleteMuteConfigRequest], empty_pb2.Empty]: + r"""Return a callable for the delete mute config method over gRPC. + + Deletes an existing mute config. If no location is + specified, default is global. + + Returns: + Callable[[~.DeleteMuteConfigRequest], + ~.Empty]: + 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_mute_config" not in self._stubs: + self._stubs["delete_mute_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/DeleteMuteConfig", + request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_mute_config"] + + @property + def delete_notification_config( + self, + ) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], empty_pb2.Empty + ]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + ~.Empty]: + 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_notification_config" not in self._stubs: + self._stubs["delete_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/DeleteNotificationConfig", + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_notification_config"] + + @property + def delete_resource_value_config( + self, + ) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], empty_pb2.Empty + ]: + r"""Return a callable for the delete resource value config method over gRPC. + + Deletes a ResourceValueConfig. + + Returns: + Callable[[~.DeleteResourceValueConfigRequest], + ~.Empty]: + 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_resource_value_config" not in self._stubs: + self._stubs["delete_resource_value_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/DeleteResourceValueConfig", + request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_resource_value_config"] + + @property + def get_big_query_export( + self, + ) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + bigquery_export.BigQueryExport, + ]: + r"""Return a callable for the get big query export method over gRPC. + + Gets a BigQuery export. + + Returns: + Callable[[~.GetBigQueryExportRequest], + ~.BigQueryExport]: + 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_big_query_export" not in self._stubs: + self._stubs["get_big_query_export"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GetBigQueryExport", + request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs["get_big_query_export"] + + @property + def get_simulation( + self, + ) -> Callable[[securitycenter_service.GetSimulationRequest], simulation.Simulation]: + r"""Return a callable for the get simulation method over gRPC. + + Get the simulation by name or the latest simulation + for the given organization. + + Returns: + Callable[[~.GetSimulationRequest], + ~.Simulation]: + 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_simulation" not in self._stubs: + self._stubs["get_simulation"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GetSimulation", + request_serializer=securitycenter_service.GetSimulationRequest.serialize, + response_deserializer=simulation.Simulation.deserialize, + ) + return self._stubs["get_simulation"] + + @property + def get_valued_resource( + self, + ) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + valued_resource.ValuedResource, + ]: + r"""Return a callable for the get valued resource method over gRPC. + + Get the valued resource by name + + Returns: + Callable[[~.GetValuedResourceRequest], + ~.ValuedResource]: + 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_valued_resource" not in self._stubs: + self._stubs["get_valued_resource"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GetValuedResource", + request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, + response_deserializer=valued_resource.ValuedResource.deserialize, + ) + return self._stubs["get_valued_resource"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy on the specified + Source. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + 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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def get_mute_config( + self, + ) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], mute_config.MuteConfig + ]: + r"""Return a callable for the get mute config method over gRPC. + + Gets a mute config. If no location is specified, + default is global. + + Returns: + Callable[[~.GetMuteConfigRequest], + ~.MuteConfig]: + 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_mute_config" not in self._stubs: + self._stubs["get_mute_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GetMuteConfig", + request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, + response_deserializer=mute_config.MuteConfig.deserialize, + ) + return self._stubs["get_mute_config"] + + @property + def get_notification_config( + self, + ) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig, + ]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + ~.NotificationConfig]: + 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_notification_config" not in self._stubs: + self._stubs["get_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GetNotificationConfig", + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs["get_notification_config"] + + @property + def get_resource_value_config( + self, + ) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + resource_value_config.ResourceValueConfig, + ]: + r"""Return a callable for the get resource value config method over gRPC. + + Gets a ResourceValueConfig. + + Returns: + Callable[[~.GetResourceValueConfigRequest], + ~.ResourceValueConfig]: + 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_resource_value_config" not in self._stubs: + self._stubs["get_resource_value_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GetResourceValueConfig", + request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, + response_deserializer=resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs["get_resource_value_config"] + + @property + def get_source( + self, + ) -> Callable[[securitycenter_service.GetSourceRequest], source.Source]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + ~.Source]: + 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_source" not in self._stubs: + self._stubs["get_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GetSource", + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs["get_source"] + + @property + def group_findings( + self, + ) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse, + ]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties in a location. If no location is + specified, findings are assumed to be in global + + To group across all sources provide a ``-`` as the source id. + The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + - ``/v2/folders/{folder_id}/sources/-/findings`` + - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` + - ``/v2/projects/{project_id}/sources/-/findings`` + - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` + + Returns: + Callable[[~.GroupFindingsRequest], + ~.GroupFindingsResponse]: + 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 "group_findings" not in self._stubs: + self._stubs["group_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GroupFindings", + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs["group_findings"] + + @property + def list_attack_paths( + self, + ) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + securitycenter_service.ListAttackPathsResponse, + ]: + r"""Return a callable for the list attack paths method over gRPC. + + Lists the attack paths for a set of simulation + results or valued resources and filter. + + Returns: + Callable[[~.ListAttackPathsRequest], + ~.ListAttackPathsResponse]: + 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_attack_paths" not in self._stubs: + self._stubs["list_attack_paths"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/ListAttackPaths", + request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, + response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, + ) + return self._stubs["list_attack_paths"] + + @property + def list_big_query_exports( + self, + ) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + securitycenter_service.ListBigQueryExportsResponse, + ]: + r"""Return a callable for the list big query exports method over gRPC. + + Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are returned. + + Returns: + Callable[[~.ListBigQueryExportsRequest], + ~.ListBigQueryExportsResponse]: + 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_big_query_exports" not in self._stubs: + self._stubs["list_big_query_exports"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/ListBigQueryExports", + request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, + response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, + ) + return self._stubs["list_big_query_exports"] + + @property + def list_findings( + self, + ) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.ListFindingsResponse, + ]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources for a given location provide a ``-`` + as the source id. If no location is specified, finding are + assumed to be in global. The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + Returns: + Callable[[~.ListFindingsRequest], + ~.ListFindingsResponse]: + 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_findings" not in self._stubs: + self._stubs["list_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/ListFindings", + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs["list_findings"] + + @property + def list_mute_configs( + self, + ) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + securitycenter_service.ListMuteConfigsResponse, + ]: + r"""Return a callable for the list mute configs method over gRPC. + + Lists mute configs. If no location is specified, + default is global. + + Returns: + Callable[[~.ListMuteConfigsRequest], + ~.ListMuteConfigsResponse]: + 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_mute_configs" not in self._stubs: + self._stubs["list_mute_configs"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/ListMuteConfigs", + request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, + ) + return self._stubs["list_mute_configs"] + + @property + def list_notification_configs( + self, + ) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse, + ]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + ~.ListNotificationConfigsResponse]: + 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_notification_configs" not in self._stubs: + self._stubs["list_notification_configs"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/ListNotificationConfigs", + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs["list_notification_configs"] + + @property + def list_resource_value_configs( + self, + ) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + securitycenter_service.ListResourceValueConfigsResponse, + ]: + r"""Return a callable for the list resource value configs method over gRPC. + + Lists all ResourceValueConfigs. + + Returns: + Callable[[~.ListResourceValueConfigsRequest], + ~.ListResourceValueConfigsResponse]: + 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_resource_value_configs" not in self._stubs: + self._stubs["list_resource_value_configs"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/ListResourceValueConfigs", + request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, + ) + return self._stubs["list_resource_value_configs"] + + @property + def list_sources( + self, + ) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse, + ]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + ~.ListSourcesResponse]: + 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_sources" not in self._stubs: + self._stubs["list_sources"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/ListSources", + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs["list_sources"] + + @property + def list_valued_resources( + self, + ) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + securitycenter_service.ListValuedResourcesResponse, + ]: + r"""Return a callable for the list valued resources method over gRPC. + + Lists the valued resources for a set of simulation + results and filter. + + Returns: + Callable[[~.ListValuedResourcesRequest], + ~.ListValuedResourcesResponse]: + 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_valued_resources" not in self._stubs: + self._stubs["list_valued_resources"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/ListValuedResources", + request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, + response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, + ) + return self._stubs["list_valued_resources"] + + @property + def set_finding_state( + self, + ) -> Callable[[securitycenter_service.SetFindingStateRequest], finding.Finding]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. If no location is + specified, finding is assumed to be in global + + Returns: + Callable[[~.SetFindingStateRequest], + ~.Finding]: + 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 "set_finding_state" not in self._stubs: + self._stubs["set_finding_state"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/SetFindingState", + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs["set_finding_state"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + Source. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + 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 "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def set_mute( + self, + ) -> Callable[[securitycenter_service.SetMuteRequest], finding.Finding]: + r"""Return a callable for the set mute method over gRPC. + + Updates the mute state of a finding. If no location + is specified, finding is assumed to be in global + + Returns: + Callable[[~.SetMuteRequest], + ~.Finding]: + 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 "set_mute" not in self._stubs: + self._stubs["set_mute"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/SetMute", + request_serializer=securitycenter_service.SetMuteRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs["set_mute"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified source. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + 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 "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def update_big_query_export( + self, + ) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + bigquery_export.BigQueryExport, + ]: + r"""Return a callable for the update big query export method over gRPC. + + Updates a BigQuery export. + + Returns: + Callable[[~.UpdateBigQueryExportRequest], + ~.BigQueryExport]: + 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_big_query_export" not in self._stubs: + self._stubs["update_big_query_export"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/UpdateBigQueryExport", + request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs["update_big_query_export"] + + @property + def update_external_system( + self, + ) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + gcs_external_system.ExternalSystem, + ]: + r"""Return a callable for the update external system method over gRPC. + + Updates external system. This is for a given finding. + If no location is specified, finding is assumed to be in + global + + Returns: + Callable[[~.UpdateExternalSystemRequest], + ~.ExternalSystem]: + 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_external_system" not in self._stubs: + self._stubs["update_external_system"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/UpdateExternalSystem", + request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, + response_deserializer=gcs_external_system.ExternalSystem.deserialize, + ) + return self._stubs["update_external_system"] + + @property + def update_finding( + self, + ) -> Callable[[securitycenter_service.UpdateFindingRequest], gcs_finding.Finding]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. If no location is + specified, finding is assumed to be in global. The + corresponding source must exist for a finding creation + to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + ~.Finding]: + 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_finding" not in self._stubs: + self._stubs["update_finding"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/UpdateFinding", + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs["update_finding"] + + @property + def update_mute_config( + self, + ) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], gcs_mute_config.MuteConfig + ]: + r"""Return a callable for the update mute config method over gRPC. + + Updates a mute config. If no location is specified, + default is global. + + Returns: + Callable[[~.UpdateMuteConfigRequest], + ~.MuteConfig]: + 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_mute_config" not in self._stubs: + self._stubs["update_mute_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/UpdateMuteConfig", + request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs["update_mute_config"] + + @property + def update_notification_config( + self, + ) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig, + ]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + ~.NotificationConfig]: + 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_notification_config" not in self._stubs: + self._stubs["update_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/UpdateNotificationConfig", + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs["update_notification_config"] + + @property + def update_resource_value_config( + self, + ) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + gcs_resource_value_config.ResourceValueConfig, + ]: + r"""Return a callable for the update resource value config method over gRPC. + + Updates an existing ResourceValueConfigs with new + rules. + + Returns: + Callable[[~.UpdateResourceValueConfigRequest], + ~.ResourceValueConfig]: + 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_resource_value_config" not in self._stubs: + self._stubs["update_resource_value_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/UpdateResourceValueConfig", + request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, + response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs["update_resource_value_config"] + + @property + def update_security_marks( + self, + ) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks, + ]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. For Finding Security marks, + if no location is specified, finding is assumed to be in + global. Assets Security Marks can only be accessed + through global endpoint. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + ~.SecurityMarks]: + 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_security_marks" not in self._stubs: + self._stubs["update_security_marks"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/UpdateSecurityMarks", + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs["update_security_marks"] + + @property + def update_source( + self, + ) -> Callable[[securitycenter_service.UpdateSourceRequest], gcs_source.Source]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + ~.Source]: + 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_source" not in self._stubs: + self._stubs["update_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/UpdateSource", + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs["update_source"] + + def close(self): + self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # 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_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # 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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # 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_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # 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_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("SecurityCenterGrpcTransport",) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 000000000000..49f609f503b3 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,1547 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.securitycenter_v2.types import securitycenter_service, simulation +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v2.types import ( + resource_value_config as gcs_resource_value_config, +) +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource + +from .base import DEFAULT_CLIENT_INFO, SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport + + +class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): + """gRPC AsyncIO backend transport for SecurityCenter. + + V2 APIs for Security Center service. + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "securitycenter.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "securitycenter.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.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. + This argument is ignored if ``channel`` is provided. + 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def batch_create_resource_value_configs( + self, + ) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + Awaitable[securitycenter_service.BatchCreateResourceValueConfigsResponse], + ]: + r"""Return a callable for the batch create resource value + configs method over gRPC. + + Creates a ResourceValueConfig for an organization. + Maps user's tags to difference resource values for use + by the attack path simulation. + + Returns: + Callable[[~.BatchCreateResourceValueConfigsRequest], + Awaitable[~.BatchCreateResourceValueConfigsResponse]]: + 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 "batch_create_resource_value_configs" not in self._stubs: + self._stubs[ + "batch_create_resource_value_configs" + ] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/BatchCreateResourceValueConfigs", + request_serializer=securitycenter_service.BatchCreateResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.BatchCreateResourceValueConfigsResponse.deserialize, + ) + return self._stubs["batch_create_resource_value_configs"] + + @property + def bulk_mute_findings( + self, + ) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the bulk mute findings method over gRPC. + + Kicks off an LRO to bulk mute findings for a parent + based on a filter. If no location is specified, findings + are muted in global. The parent can be either an + organization, folder, or project. The findings matched + by the filter will be muted after the LRO is done. + + Returns: + Callable[[~.BulkMuteFindingsRequest], + 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 "bulk_mute_findings" not in self._stubs: + self._stubs["bulk_mute_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/BulkMuteFindings", + request_serializer=securitycenter_service.BulkMuteFindingsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["bulk_mute_findings"] + + @property + def create_big_query_export( + self, + ) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + Awaitable[bigquery_export.BigQueryExport], + ]: + r"""Return a callable for the create big query export method over gRPC. + + Creates a BigQuery export. + + Returns: + Callable[[~.CreateBigQueryExportRequest], + Awaitable[~.BigQueryExport]]: + 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_big_query_export" not in self._stubs: + self._stubs["create_big_query_export"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/CreateBigQueryExport", + request_serializer=securitycenter_service.CreateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs["create_big_query_export"] + + @property + def create_finding( + self, + ) -> Callable[ + [securitycenter_service.CreateFindingRequest], Awaitable[gcs_finding.Finding] + ]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding in a location. The corresponding + source must exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + Awaitable[~.Finding]]: + 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_finding" not in self._stubs: + self._stubs["create_finding"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/CreateFinding", + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs["create_finding"] + + @property + def create_mute_config( + self, + ) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], + Awaitable[gcs_mute_config.MuteConfig], + ]: + r"""Return a callable for the create mute config method over gRPC. + + Creates a mute config. + + Returns: + Callable[[~.CreateMuteConfigRequest], + Awaitable[~.MuteConfig]]: + 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_mute_config" not in self._stubs: + self._stubs["create_mute_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/CreateMuteConfig", + request_serializer=securitycenter_service.CreateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs["create_mute_config"] + + @property + def create_notification_config( + self, + ) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig], + ]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + 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_notification_config" not in self._stubs: + self._stubs["create_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/CreateNotificationConfig", + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs["create_notification_config"] + + @property + def create_source( + self, + ) -> Callable[ + [securitycenter_service.CreateSourceRequest], Awaitable[gcs_source.Source] + ]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + Awaitable[~.Source]]: + 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_source" not in self._stubs: + self._stubs["create_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/CreateSource", + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs["create_source"] + + @property + def delete_big_query_export( + self, + ) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete big query export method over gRPC. + + Deletes an existing BigQuery export. + + Returns: + Callable[[~.DeleteBigQueryExportRequest], + Awaitable[~.Empty]]: + 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_big_query_export" not in self._stubs: + self._stubs["delete_big_query_export"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/DeleteBigQueryExport", + request_serializer=securitycenter_service.DeleteBigQueryExportRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_big_query_export"] + + @property + def delete_mute_config( + self, + ) -> Callable[ + [securitycenter_service.DeleteMuteConfigRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete mute config method over gRPC. + + Deletes an existing mute config. If no location is + specified, default is global. + + Returns: + Callable[[~.DeleteMuteConfigRequest], + Awaitable[~.Empty]]: + 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_mute_config" not in self._stubs: + self._stubs["delete_mute_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/DeleteMuteConfig", + request_serializer=securitycenter_service.DeleteMuteConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_mute_config"] + + @property + def delete_notification_config( + self, + ) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Awaitable[empty_pb2.Empty], + ]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + Awaitable[~.Empty]]: + 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_notification_config" not in self._stubs: + self._stubs["delete_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/DeleteNotificationConfig", + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_notification_config"] + + @property + def delete_resource_value_config( + self, + ) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], + Awaitable[empty_pb2.Empty], + ]: + r"""Return a callable for the delete resource value config method over gRPC. + + Deletes a ResourceValueConfig. + + Returns: + Callable[[~.DeleteResourceValueConfigRequest], + Awaitable[~.Empty]]: + 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_resource_value_config" not in self._stubs: + self._stubs["delete_resource_value_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/DeleteResourceValueConfig", + request_serializer=securitycenter_service.DeleteResourceValueConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_resource_value_config"] + + @property + def get_big_query_export( + self, + ) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + Awaitable[bigquery_export.BigQueryExport], + ]: + r"""Return a callable for the get big query export method over gRPC. + + Gets a BigQuery export. + + Returns: + Callable[[~.GetBigQueryExportRequest], + Awaitable[~.BigQueryExport]]: + 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_big_query_export" not in self._stubs: + self._stubs["get_big_query_export"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GetBigQueryExport", + request_serializer=securitycenter_service.GetBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs["get_big_query_export"] + + @property + def get_simulation( + self, + ) -> Callable[ + [securitycenter_service.GetSimulationRequest], Awaitable[simulation.Simulation] + ]: + r"""Return a callable for the get simulation method over gRPC. + + Get the simulation by name or the latest simulation + for the given organization. + + Returns: + Callable[[~.GetSimulationRequest], + Awaitable[~.Simulation]]: + 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_simulation" not in self._stubs: + self._stubs["get_simulation"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GetSimulation", + request_serializer=securitycenter_service.GetSimulationRequest.serialize, + response_deserializer=simulation.Simulation.deserialize, + ) + return self._stubs["get_simulation"] + + @property + def get_valued_resource( + self, + ) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + Awaitable[valued_resource.ValuedResource], + ]: + r"""Return a callable for the get valued resource method over gRPC. + + Get the valued resource by name + + Returns: + Callable[[~.GetValuedResourceRequest], + Awaitable[~.ValuedResource]]: + 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_valued_resource" not in self._stubs: + self._stubs["get_valued_resource"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GetValuedResource", + request_serializer=securitycenter_service.GetValuedResourceRequest.serialize, + response_deserializer=valued_resource.ValuedResource.deserialize, + ) + return self._stubs["get_valued_resource"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy on the specified + Source. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + 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_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def get_mute_config( + self, + ) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], Awaitable[mute_config.MuteConfig] + ]: + r"""Return a callable for the get mute config method over gRPC. + + Gets a mute config. If no location is specified, + default is global. + + Returns: + Callable[[~.GetMuteConfigRequest], + Awaitable[~.MuteConfig]]: + 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_mute_config" not in self._stubs: + self._stubs["get_mute_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GetMuteConfig", + request_serializer=securitycenter_service.GetMuteConfigRequest.serialize, + response_deserializer=mute_config.MuteConfig.deserialize, + ) + return self._stubs["get_mute_config"] + + @property + def get_notification_config( + self, + ) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Awaitable[notification_config.NotificationConfig], + ]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + 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_notification_config" not in self._stubs: + self._stubs["get_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GetNotificationConfig", + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs["get_notification_config"] + + @property + def get_resource_value_config( + self, + ) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + Awaitable[resource_value_config.ResourceValueConfig], + ]: + r"""Return a callable for the get resource value config method over gRPC. + + Gets a ResourceValueConfig. + + Returns: + Callable[[~.GetResourceValueConfigRequest], + Awaitable[~.ResourceValueConfig]]: + 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_resource_value_config" not in self._stubs: + self._stubs["get_resource_value_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GetResourceValueConfig", + request_serializer=securitycenter_service.GetResourceValueConfigRequest.serialize, + response_deserializer=resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs["get_resource_value_config"] + + @property + def get_source( + self, + ) -> Callable[[securitycenter_service.GetSourceRequest], Awaitable[source.Source]]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + Awaitable[~.Source]]: + 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_source" not in self._stubs: + self._stubs["get_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GetSource", + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs["get_source"] + + @property + def group_findings( + self, + ) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Awaitable[securitycenter_service.GroupFindingsResponse], + ]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties in a location. If no location is + specified, findings are assumed to be in global + + To group across all sources provide a ``-`` as the source id. + The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + - ``/v2/folders/{folder_id}/sources/-/findings`` + - ``/v2/folders/{folder_id}/sources/-/locations/{location_id}/findings`` + - ``/v2/projects/{project_id}/sources/-/findings`` + - ``/v2/projects/{project_id}/sources/-/locations/{location_id}/findings`` + + Returns: + Callable[[~.GroupFindingsRequest], + Awaitable[~.GroupFindingsResponse]]: + 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 "group_findings" not in self._stubs: + self._stubs["group_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/GroupFindings", + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs["group_findings"] + + @property + def list_attack_paths( + self, + ) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + Awaitable[securitycenter_service.ListAttackPathsResponse], + ]: + r"""Return a callable for the list attack paths method over gRPC. + + Lists the attack paths for a set of simulation + results or valued resources and filter. + + Returns: + Callable[[~.ListAttackPathsRequest], + Awaitable[~.ListAttackPathsResponse]]: + 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_attack_paths" not in self._stubs: + self._stubs["list_attack_paths"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/ListAttackPaths", + request_serializer=securitycenter_service.ListAttackPathsRequest.serialize, + response_deserializer=securitycenter_service.ListAttackPathsResponse.deserialize, + ) + return self._stubs["list_attack_paths"] + + @property + def list_big_query_exports( + self, + ) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + Awaitable[securitycenter_service.ListBigQueryExportsResponse], + ]: + r"""Return a callable for the list big query exports method over gRPC. + + Lists BigQuery exports. Note that when requesting + BigQuery exports at a given level all exports under that + level are also returned e.g. if requesting BigQuery + exports under a folder, then all BigQuery exports + immediately under the folder plus the ones created under + the projects within the folder are returned. + + Returns: + Callable[[~.ListBigQueryExportsRequest], + Awaitable[~.ListBigQueryExportsResponse]]: + 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_big_query_exports" not in self._stubs: + self._stubs["list_big_query_exports"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/ListBigQueryExports", + request_serializer=securitycenter_service.ListBigQueryExportsRequest.serialize, + response_deserializer=securitycenter_service.ListBigQueryExportsResponse.deserialize, + ) + return self._stubs["list_big_query_exports"] + + @property + def list_findings( + self, + ) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Awaitable[securitycenter_service.ListFindingsResponse], + ]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources for a given location provide a ``-`` + as the source id. If no location is specified, finding are + assumed to be in global. The following list shows some examples: + + - ``/v2/organizations/{organization_id}/sources/-/findings`` + - + + ``/v2/organizations/{organization_id}/sources/-/locations/{location_id}/findings`` + + Returns: + Callable[[~.ListFindingsRequest], + Awaitable[~.ListFindingsResponse]]: + 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_findings" not in self._stubs: + self._stubs["list_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/ListFindings", + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs["list_findings"] + + @property + def list_mute_configs( + self, + ) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + Awaitable[securitycenter_service.ListMuteConfigsResponse], + ]: + r"""Return a callable for the list mute configs method over gRPC. + + Lists mute configs. If no location is specified, + default is global. + + Returns: + Callable[[~.ListMuteConfigsRequest], + Awaitable[~.ListMuteConfigsResponse]]: + 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_mute_configs" not in self._stubs: + self._stubs["list_mute_configs"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/ListMuteConfigs", + request_serializer=securitycenter_service.ListMuteConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListMuteConfigsResponse.deserialize, + ) + return self._stubs["list_mute_configs"] + + @property + def list_notification_configs( + self, + ) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Awaitable[securitycenter_service.ListNotificationConfigsResponse], + ]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + Awaitable[~.ListNotificationConfigsResponse]]: + 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_notification_configs" not in self._stubs: + self._stubs["list_notification_configs"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/ListNotificationConfigs", + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs["list_notification_configs"] + + @property + def list_resource_value_configs( + self, + ) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + Awaitable[securitycenter_service.ListResourceValueConfigsResponse], + ]: + r"""Return a callable for the list resource value configs method over gRPC. + + Lists all ResourceValueConfigs. + + Returns: + Callable[[~.ListResourceValueConfigsRequest], + Awaitable[~.ListResourceValueConfigsResponse]]: + 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_resource_value_configs" not in self._stubs: + self._stubs["list_resource_value_configs"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/ListResourceValueConfigs", + request_serializer=securitycenter_service.ListResourceValueConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListResourceValueConfigsResponse.deserialize, + ) + return self._stubs["list_resource_value_configs"] + + @property + def list_sources( + self, + ) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Awaitable[securitycenter_service.ListSourcesResponse], + ]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + Awaitable[~.ListSourcesResponse]]: + 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_sources" not in self._stubs: + self._stubs["list_sources"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/ListSources", + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs["list_sources"] + + @property + def list_valued_resources( + self, + ) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + Awaitable[securitycenter_service.ListValuedResourcesResponse], + ]: + r"""Return a callable for the list valued resources method over gRPC. + + Lists the valued resources for a set of simulation + results and filter. + + Returns: + Callable[[~.ListValuedResourcesRequest], + Awaitable[~.ListValuedResourcesResponse]]: + 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_valued_resources" not in self._stubs: + self._stubs["list_valued_resources"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/ListValuedResources", + request_serializer=securitycenter_service.ListValuedResourcesRequest.serialize, + response_deserializer=securitycenter_service.ListValuedResourcesResponse.deserialize, + ) + return self._stubs["list_valued_resources"] + + @property + def set_finding_state( + self, + ) -> Callable[ + [securitycenter_service.SetFindingStateRequest], Awaitable[finding.Finding] + ]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. If no location is + specified, finding is assumed to be in global + + Returns: + Callable[[~.SetFindingStateRequest], + Awaitable[~.Finding]]: + 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 "set_finding_state" not in self._stubs: + self._stubs["set_finding_state"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/SetFindingState", + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs["set_finding_state"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + Source. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + 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 "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def set_mute( + self, + ) -> Callable[[securitycenter_service.SetMuteRequest], Awaitable[finding.Finding]]: + r"""Return a callable for the set mute method over gRPC. + + Updates the mute state of a finding. If no location + is specified, finding is assumed to be in global + + Returns: + Callable[[~.SetMuteRequest], + Awaitable[~.Finding]]: + 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 "set_mute" not in self._stubs: + self._stubs["set_mute"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/SetMute", + request_serializer=securitycenter_service.SetMuteRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs["set_mute"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified source. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + 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 "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def update_big_query_export( + self, + ) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + Awaitable[bigquery_export.BigQueryExport], + ]: + r"""Return a callable for the update big query export method over gRPC. + + Updates a BigQuery export. + + Returns: + Callable[[~.UpdateBigQueryExportRequest], + Awaitable[~.BigQueryExport]]: + 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_big_query_export" not in self._stubs: + self._stubs["update_big_query_export"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/UpdateBigQueryExport", + request_serializer=securitycenter_service.UpdateBigQueryExportRequest.serialize, + response_deserializer=bigquery_export.BigQueryExport.deserialize, + ) + return self._stubs["update_big_query_export"] + + @property + def update_external_system( + self, + ) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + Awaitable[gcs_external_system.ExternalSystem], + ]: + r"""Return a callable for the update external system method over gRPC. + + Updates external system. This is for a given finding. + If no location is specified, finding is assumed to be in + global + + Returns: + Callable[[~.UpdateExternalSystemRequest], + Awaitable[~.ExternalSystem]]: + 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_external_system" not in self._stubs: + self._stubs["update_external_system"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/UpdateExternalSystem", + request_serializer=securitycenter_service.UpdateExternalSystemRequest.serialize, + response_deserializer=gcs_external_system.ExternalSystem.deserialize, + ) + return self._stubs["update_external_system"] + + @property + def update_finding( + self, + ) -> Callable[ + [securitycenter_service.UpdateFindingRequest], Awaitable[gcs_finding.Finding] + ]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. If no location is + specified, finding is assumed to be in global. The + corresponding source must exist for a finding creation + to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + Awaitable[~.Finding]]: + 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_finding" not in self._stubs: + self._stubs["update_finding"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/UpdateFinding", + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs["update_finding"] + + @property + def update_mute_config( + self, + ) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], + Awaitable[gcs_mute_config.MuteConfig], + ]: + r"""Return a callable for the update mute config method over gRPC. + + Updates a mute config. If no location is specified, + default is global. + + Returns: + Callable[[~.UpdateMuteConfigRequest], + Awaitable[~.MuteConfig]]: + 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_mute_config" not in self._stubs: + self._stubs["update_mute_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/UpdateMuteConfig", + request_serializer=securitycenter_service.UpdateMuteConfigRequest.serialize, + response_deserializer=gcs_mute_config.MuteConfig.deserialize, + ) + return self._stubs["update_mute_config"] + + @property + def update_notification_config( + self, + ) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig], + ]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + 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_notification_config" not in self._stubs: + self._stubs["update_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/UpdateNotificationConfig", + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs["update_notification_config"] + + @property + def update_resource_value_config( + self, + ) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + Awaitable[gcs_resource_value_config.ResourceValueConfig], + ]: + r"""Return a callable for the update resource value config method over gRPC. + + Updates an existing ResourceValueConfigs with new + rules. + + Returns: + Callable[[~.UpdateResourceValueConfigRequest], + Awaitable[~.ResourceValueConfig]]: + 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_resource_value_config" not in self._stubs: + self._stubs["update_resource_value_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/UpdateResourceValueConfig", + request_serializer=securitycenter_service.UpdateResourceValueConfigRequest.serialize, + response_deserializer=gcs_resource_value_config.ResourceValueConfig.deserialize, + ) + return self._stubs["update_resource_value_config"] + + @property + def update_security_marks( + self, + ) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Awaitable[gcs_security_marks.SecurityMarks], + ]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. For Finding Security marks, + if no location is specified, finding is assumed to be in + global. Assets Security Marks can only be accessed + through global endpoint. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + Awaitable[~.SecurityMarks]]: + 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_security_marks" not in self._stubs: + self._stubs["update_security_marks"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/UpdateSecurityMarks", + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs["update_security_marks"] + + @property + def update_source( + self, + ) -> Callable[ + [securitycenter_service.UpdateSourceRequest], Awaitable[gcs_source.Source] + ]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + Awaitable[~.Source]]: + 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_source" not in self._stubs: + self._stubs["update_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v2.SecurityCenter/UpdateSource", + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs["update_source"] + + def close(self): + return self.grpc_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # 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_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # 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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # 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_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # 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_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("SecurityCenterGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/transports/rest.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/transports/rest.py new file mode 100644 index 000000000000..92371b027a00 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/transports/rest.py @@ -0,0 +1,6583 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import ( + gapic_v1, + operations_v1, + path_template, + rest_helpers, + rest_streaming, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.securitycenter_v2.types import securitycenter_service, simulation +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v2.types import ( + resource_value_config as gcs_resource_value_config, +) +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import bigquery_export +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import SecurityCenterTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SecurityCenterRestInterceptor: + """Interceptor for SecurityCenter. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the SecurityCenterRestTransport. + + .. code-block:: python + class MyCustomSecurityCenterInterceptor(SecurityCenterRestInterceptor): + def pre_batch_create_resource_value_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_resource_value_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_bulk_mute_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_bulk_mute_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_big_query_export(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_mute_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_resource_value_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_big_query_export(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_mute_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_resource_value_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_resource_value_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_simulation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_simulation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_source(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_valued_resource(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_valued_resource(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_group_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_group_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_attack_paths(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_attack_paths(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_big_query_exports(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_big_query_exports(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_mute_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_mute_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_notification_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_notification_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_resource_value_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_resource_value_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_valued_resources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_valued_resources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_finding_state(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_finding_state(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_mute(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_mute(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_big_query_export(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_big_query_export(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_external_system(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_external_system(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_mute_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_mute_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_notification_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_notification_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_resource_value_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_resource_value_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_security_marks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_security_marks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_source(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_source(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SecurityCenterRestTransport(interceptor=MyCustomSecurityCenterInterceptor()) + client = SecurityCenterClient(transport=transport) + + + """ + + def pre_batch_create_resource_value_configs( + self, + request: securitycenter_service.BatchCreateResourceValueConfigsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.BatchCreateResourceValueConfigsRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for batch_create_resource_value_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_batch_create_resource_value_configs( + self, response: securitycenter_service.BatchCreateResourceValueConfigsResponse + ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + """Post-rpc interceptor for batch_create_resource_value_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_bulk_mute_findings( + self, + request: securitycenter_service.BulkMuteFindingsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.BulkMuteFindingsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for bulk_mute_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_bulk_mute_findings( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for bulk_mute_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_create_big_query_export( + self, + request: securitycenter_service.CreateBigQueryExportRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.CreateBigQueryExportRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for create_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_big_query_export( + self, response: bigquery_export.BigQueryExport + ) -> bigquery_export.BigQueryExport: + """Post-rpc interceptor for create_big_query_export + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_create_finding( + self, + request: securitycenter_service.CreateFindingRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[securitycenter_service.CreateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for create_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_create_mute_config( + self, + request: securitycenter_service.CreateMuteConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.CreateMuteConfigRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for create_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_mute_config( + self, response: gcs_mute_config.MuteConfig + ) -> gcs_mute_config.MuteConfig: + """Post-rpc interceptor for create_mute_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_create_notification_config( + self, + request: securitycenter_service.CreateNotificationConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.CreateNotificationConfigRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for create_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_notification_config( + self, response: gcs_notification_config.NotificationConfig + ) -> gcs_notification_config.NotificationConfig: + """Post-rpc interceptor for create_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_create_source( + self, + request: securitycenter_service.CreateSourceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[securitycenter_service.CreateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_create_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for create_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_delete_big_query_export( + self, + request: securitycenter_service.DeleteBigQueryExportRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.DeleteBigQueryExportRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for delete_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_mute_config( + self, + request: securitycenter_service.DeleteMuteConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.DeleteMuteConfigRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for delete_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_notification_config( + self, + request: securitycenter_service.DeleteNotificationConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.DeleteNotificationConfigRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for delete_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_delete_resource_value_config( + self, + request: securitycenter_service.DeleteResourceValueConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.DeleteResourceValueConfigRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for delete_resource_value_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def pre_get_big_query_export( + self, + request: securitycenter_service.GetBigQueryExportRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.GetBigQueryExportRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for get_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_big_query_export( + self, response: bigquery_export.BigQueryExport + ) -> bigquery_export.BigQueryExport: + """Post-rpc interceptor for get_big_query_export + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_get_mute_config( + self, + request: securitycenter_service.GetMuteConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[securitycenter_service.GetMuteConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_mute_config( + self, response: mute_config.MuteConfig + ) -> mute_config.MuteConfig: + """Post-rpc interceptor for get_mute_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_get_notification_config( + self, + request: securitycenter_service.GetNotificationConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.GetNotificationConfigRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for get_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_notification_config( + self, response: notification_config.NotificationConfig + ) -> notification_config.NotificationConfig: + """Post-rpc interceptor for get_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_get_resource_value_config( + self, + request: securitycenter_service.GetResourceValueConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.GetResourceValueConfigRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for get_resource_value_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_resource_value_config( + self, response: resource_value_config.ResourceValueConfig + ) -> resource_value_config.ResourceValueConfig: + """Post-rpc interceptor for get_resource_value_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_get_simulation( + self, + request: securitycenter_service.GetSimulationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[securitycenter_service.GetSimulationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_simulation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_simulation( + self, response: simulation.Simulation + ) -> simulation.Simulation: + """Post-rpc interceptor for get_simulation + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_get_source( + self, + request: securitycenter_service.GetSourceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[securitycenter_service.GetSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_source(self, response: source.Source) -> source.Source: + """Post-rpc interceptor for get_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_get_valued_resource( + self, + request: securitycenter_service.GetValuedResourceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.GetValuedResourceRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for get_valued_resource + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_get_valued_resource( + self, response: valued_resource.ValuedResource + ) -> valued_resource.ValuedResource: + """Post-rpc interceptor for get_valued_resource + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_group_findings( + self, + request: securitycenter_service.GroupFindingsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[securitycenter_service.GroupFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for group_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_group_findings( + self, response: securitycenter_service.GroupFindingsResponse + ) -> securitycenter_service.GroupFindingsResponse: + """Post-rpc interceptor for group_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_list_attack_paths( + self, + request: securitycenter_service.ListAttackPathsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.ListAttackPathsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_attack_paths + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_attack_paths( + self, response: securitycenter_service.ListAttackPathsResponse + ) -> securitycenter_service.ListAttackPathsResponse: + """Post-rpc interceptor for list_attack_paths + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_list_big_query_exports( + self, + request: securitycenter_service.ListBigQueryExportsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.ListBigQueryExportsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_big_query_exports + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_big_query_exports( + self, response: securitycenter_service.ListBigQueryExportsResponse + ) -> securitycenter_service.ListBigQueryExportsResponse: + """Post-rpc interceptor for list_big_query_exports + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_list_findings( + self, + request: securitycenter_service.ListFindingsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[securitycenter_service.ListFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_findings( + self, response: securitycenter_service.ListFindingsResponse + ) -> securitycenter_service.ListFindingsResponse: + """Post-rpc interceptor for list_findings + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_list_mute_configs( + self, + request: securitycenter_service.ListMuteConfigsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.ListMuteConfigsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_mute_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_mute_configs( + self, response: securitycenter_service.ListMuteConfigsResponse + ) -> securitycenter_service.ListMuteConfigsResponse: + """Post-rpc interceptor for list_mute_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_list_notification_configs( + self, + request: securitycenter_service.ListNotificationConfigsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.ListNotificationConfigsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_notification_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_notification_configs( + self, response: securitycenter_service.ListNotificationConfigsResponse + ) -> securitycenter_service.ListNotificationConfigsResponse: + """Post-rpc interceptor for list_notification_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_list_resource_value_configs( + self, + request: securitycenter_service.ListResourceValueConfigsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.ListResourceValueConfigsRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for list_resource_value_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_resource_value_configs( + self, response: securitycenter_service.ListResourceValueConfigsResponse + ) -> securitycenter_service.ListResourceValueConfigsResponse: + """Post-rpc interceptor for list_resource_value_configs + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_list_sources( + self, + request: securitycenter_service.ListSourcesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[securitycenter_service.ListSourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_sources + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_sources( + self, response: securitycenter_service.ListSourcesResponse + ) -> securitycenter_service.ListSourcesResponse: + """Post-rpc interceptor for list_sources + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_list_valued_resources( + self, + request: securitycenter_service.ListValuedResourcesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.ListValuedResourcesRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_valued_resources + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_list_valued_resources( + self, response: securitycenter_service.ListValuedResourcesResponse + ) -> securitycenter_service.ListValuedResourcesResponse: + """Post-rpc interceptor for list_valued_resources + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_set_finding_state( + self, + request: securitycenter_service.SetFindingStateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.SetFindingStateRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_set_finding_state(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for set_finding_state + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_set_mute( + self, + request: securitycenter_service.SetMuteRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[securitycenter_service.SetMuteRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_mute + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_set_mute(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for set_mute + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_update_big_query_export( + self, + request: securitycenter_service.UpdateBigQueryExportRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.UpdateBigQueryExportRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_big_query_export + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_big_query_export( + self, response: bigquery_export.BigQueryExport + ) -> bigquery_export.BigQueryExport: + """Post-rpc interceptor for update_big_query_export + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_update_external_system( + self, + request: securitycenter_service.UpdateExternalSystemRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.UpdateExternalSystemRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_external_system + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_external_system( + self, response: gcs_external_system.ExternalSystem + ) -> gcs_external_system.ExternalSystem: + """Post-rpc interceptor for update_external_system + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_update_finding( + self, + request: securitycenter_service.UpdateFindingRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[securitycenter_service.UpdateFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_finding(self, response: gcs_finding.Finding) -> gcs_finding.Finding: + """Post-rpc interceptor for update_finding + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_update_mute_config( + self, + request: securitycenter_service.UpdateMuteConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.UpdateMuteConfigRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_mute_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_mute_config( + self, response: gcs_mute_config.MuteConfig + ) -> gcs_mute_config.MuteConfig: + """Post-rpc interceptor for update_mute_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_update_notification_config( + self, + request: securitycenter_service.UpdateNotificationConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.UpdateNotificationConfigRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for update_notification_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_notification_config( + self, response: gcs_notification_config.NotificationConfig + ) -> gcs_notification_config.NotificationConfig: + """Post-rpc interceptor for update_notification_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_update_resource_value_config( + self, + request: securitycenter_service.UpdateResourceValueConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.UpdateResourceValueConfigRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for update_resource_value_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_resource_value_config( + self, response: gcs_resource_value_config.ResourceValueConfig + ) -> gcs_resource_value_config.ResourceValueConfig: + """Post-rpc interceptor for update_resource_value_config + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_update_security_marks( + self, + request: securitycenter_service.UpdateSecurityMarksRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + securitycenter_service.UpdateSecurityMarksRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_security_marks( + self, response: gcs_security_marks.SecurityMarks + ) -> gcs_security_marks.SecurityMarks: + """Post-rpc interceptor for update_security_marks + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter server but before + it is returned to user code. + """ + return response + + def pre_update_source( + self, + request: securitycenter_service.UpdateSourceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[securitycenter_service.UpdateSourceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecurityCenter server. + """ + return request, metadata + + def post_update_source(self, response: gcs_source.Source) -> gcs_source.Source: + """Post-rpc interceptor for update_source + + Override in a subclass to manipulate the response + after it is returned by the SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter 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 SecurityCenter server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SecurityCenterRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SecurityCenterRestInterceptor + + +class SecurityCenterRestTransport(SecurityCenterTransport): + """REST backend transport for SecurityCenter. + + V2 APIs for Security Center service. + + 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 = "securitycenter.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[SecurityCenterRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'securitycenter.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 + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + 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 SecurityCenterRestInterceptor() + 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": "/v2/{name=organizations/*/operations/*}:cancel", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v2/{name=organizations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v2/{name=organizations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v2/{name=organizations/*/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="v2", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _BatchCreateResourceValueConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("BatchCreateResourceValueConfigs") + + __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 + } + + def __call__( + self, + request: securitycenter_service.BatchCreateResourceValueConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.BatchCreateResourceValueConfigsResponse: + r"""Call the batch create resource + value configs method over HTTP. + + Args: + request (~.securitycenter_service.BatchCreateResourceValueConfigsRequest): + The request object. Request message to create multiple + resource value configs + 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: + ~.securitycenter_service.BatchCreateResourceValueConfigsResponse: + Response message for + BatchCreateResourceValueConfigs + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=organizations/*}/resourceValueConfigs:batchCreate", + "body": "*", + }, + ] + ( + request, + metadata, + ) = self._interceptor.pre_batch_create_resource_value_configs( + request, metadata + ) + pb_request = ( + securitycenter_service.BatchCreateResourceValueConfigsRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = securitycenter_service.BatchCreateResourceValueConfigsResponse() + pb_resp = securitycenter_service.BatchCreateResourceValueConfigsResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_create_resource_value_configs(resp) + return resp + + class _BulkMuteFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("BulkMuteFindings") + + __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 + } + + def __call__( + self, + request: securitycenter_service.BulkMuteFindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the bulk mute findings method over HTTP. + + Args: + request (~.securitycenter_service.BulkMuteFindingsRequest): + The request object. Request message for bulk findings + update. + Note: + + 1. If multiple bulk update requests + match the same resource, the order + in which they get executed is not + defined. + 2. Once a bulk operation is started, + there is no way to stop it. + 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: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=organizations/*}/findings:bulkMute", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=organizations/*/locations/*}/findings:bulkMute", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=folders/*}/findings:bulkMute", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=folders/*/locations/*}/findings:bulkMute", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*}/findings:bulkMute", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/findings:bulkMute", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_bulk_mute_findings( + request, metadata + ) + pb_request = securitycenter_service.BulkMuteFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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_bulk_mute_findings(resp) + return resp + + class _CreateBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateBigQueryExport") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "bigQueryExportId": "", + } + + @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 + } + + def __call__( + self, + request: securitycenter_service.CreateBigQueryExportRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Call the create big query export method over HTTP. + + Args: + request (~.securitycenter_service.CreateBigQueryExportRequest): + The request object. Request message for creating a + BigQuery export. + 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: + ~.bigquery_export.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=organizations/*/locations/*}/bigQueryExports", + "body": "big_query_export", + }, + { + "method": "post", + "uri": "/v2/{parent=folders/*/locations/*}/bigQueryExports", + "body": "big_query_export", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/bigQueryExports", + "body": "big_query_export", + }, + ] + request, metadata = self._interceptor.pre_create_big_query_export( + request, metadata + ) + pb_request = securitycenter_service.CreateBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = bigquery_export.BigQueryExport() + pb_resp = bigquery_export.BigQueryExport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_big_query_export(resp) + return resp + + class _CreateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "findingId": "", + } + + @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 + } + + def __call__( + self, + request: securitycenter_service.CreateFindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Call the create finding method over HTTP. + + Args: + request (~.securitycenter_service.CreateFindingRequest): + The request object. Request message for creating a + finding. + 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: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=organizations/*/sources/*/locations/*}/findings", + "body": "finding", + }, + { + "method": "post", + "uri": "/v2/{parent=organizations/*/sources/*}/findings", + "body": "finding", + }, + ] + request, metadata = self._interceptor.pre_create_finding(request, metadata) + pb_request = securitycenter_service.CreateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_finding(resp) + return resp + + class _CreateMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateMuteConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "muteConfigId": "", + } + + @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 + } + + def __call__( + self, + request: securitycenter_service.CreateMuteConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Call the create mute config method over HTTP. + + Args: + request (~.securitycenter_service.CreateMuteConfigRequest): + The request object. Request message for creating a mute + config. + 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: + ~.gcs_mute_config.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=organizations/*/locations/*}/muteConfigs", + "body": "mute_config", + }, + { + "method": "post", + "uri": "/v2/{parent=folders/*/locations/*}/muteConfigs", + "body": "mute_config", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/muteConfigs", + "body": "mute_config", + }, + { + "method": "post", + "uri": "/v2/{parent=organizations/*}/muteConfigs", + "body": "mute_config", + }, + { + "method": "post", + "uri": "/v2/{parent=folders/*}/muteConfigs", + "body": "mute_config", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*}/muteConfigs", + "body": "mute_config", + }, + ] + request, metadata = self._interceptor.pre_create_mute_config( + request, metadata + ) + pb_request = securitycenter_service.CreateMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gcs_mute_config.MuteConfig() + pb_resp = gcs_mute_config.MuteConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_mute_config(resp) + return resp + + class _CreateNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateNotificationConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "configId": "", + } + + @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 + } + + def __call__( + self, + request: securitycenter_service.CreateNotificationConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Call the create notification + config method over HTTP. + + Args: + request (~.securitycenter_service.CreateNotificationConfigRequest): + The request object. Request message for creating a + notification config. + 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: + ~.gcs_notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=organizations/*/locations/*}/notificationConfigs", + "body": "notification_config", + }, + { + "method": "post", + "uri": "/v2/{parent=folders/*/locations/*}/notificationConfigs", + "body": "notification_config", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/notificationConfigs", + "body": "notification_config", + }, + ] + request, metadata = self._interceptor.pre_create_notification_config( + request, metadata + ) + pb_request = securitycenter_service.CreateNotificationConfigRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gcs_notification_config.NotificationConfig() + pb_resp = gcs_notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_notification_config(resp) + return resp + + class _CreateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("CreateSource") + + __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 + } + + def __call__( + self, + request: securitycenter_service.CreateSourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Call the create source method over HTTP. + + Args: + request (~.securitycenter_service.CreateSourceRequest): + The request object. Request message for creating a + source. + 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: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=organizations/*}/sources", + "body": "source", + }, + ] + request, metadata = self._interceptor.pre_create_source(request, metadata) + pb_request = securitycenter_service.CreateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_source(resp) + return resp + + class _DeleteBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteBigQueryExport") + + __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 + } + + def __call__( + self, + request: securitycenter_service.DeleteBigQueryExportRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete big query export method over HTTP. + + Args: + request (~.securitycenter_service.DeleteBigQueryExportRequest): + The request object. Request message for deleting a + BigQuery export. + 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=organizations/*/locations/*/bigQueryExports/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=folders/*/locations/*/bigQueryExports/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/bigQueryExports/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_big_query_export( + request, metadata + ) + pb_request = securitycenter_service.DeleteBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteMuteConfig") + + __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 + } + + def __call__( + self, + request: securitycenter_service.DeleteMuteConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete mute config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteMuteConfigRequest): + The request object. Request message for deleting a mute + config. If no location is specified, + default is global. + 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=organizations/*/muteConfigs/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=organizations/*/locations/*/muteConfigs/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=folders/*/muteConfigs/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=folders/*/locations/*/muteConfigs/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=projects/*/muteConfigs/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/muteConfigs/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_mute_config( + request, metadata + ) + pb_request = securitycenter_service.DeleteMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteNotificationConfig") + + __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 + } + + def __call__( + self, + request: securitycenter_service.DeleteNotificationConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete notification + config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteNotificationConfigRequest): + The request object. Request message for deleting a + notification config. + 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=organizations/*/locations/*/notificationConfigs/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=folders/*/locations/*/notificationConfigs/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/notificationConfigs/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_notification_config( + request, metadata + ) + pb_request = securitycenter_service.DeleteNotificationConfigRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteResourceValueConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("DeleteResourceValueConfig") + + __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 + } + + def __call__( + self, + request: securitycenter_service.DeleteResourceValueConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete resource value + config method over HTTP. + + Args: + request (~.securitycenter_service.DeleteResourceValueConfigRequest): + The request object. Request message to delete resource + value config + 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=organizations/*/resourceValueConfigs/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_resource_value_config( + request, metadata + ) + pb_request = securitycenter_service.DeleteResourceValueConfigRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("GetBigQueryExport") + + __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 + } + + def __call__( + self, + request: securitycenter_service.GetBigQueryExportRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Call the get big query export method over HTTP. + + Args: + request (~.securitycenter_service.GetBigQueryExportRequest): + The request object. Request message for retrieving a + BigQuery export. + 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: + ~.bigquery_export.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=organizations/*/locations/*/bigQueryExports/*}", + }, + { + "method": "get", + "uri": "/v2/{name=folders/*/locations/*/bigQueryExports/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/bigQueryExports/*}", + }, + ] + request, metadata = self._interceptor.pre_get_big_query_export( + request, metadata + ) + pb_request = securitycenter_service.GetBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = bigquery_export.BigQueryExport() + pb_resp = bigquery_export.BigQueryExport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_big_query_export(resp) + return resp + + class _GetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __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 + } + + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (~.iam_policy_pb2.GetIamPolicyRequest): + The request object. Request message for ``GetIamPolicy`` 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: + ~.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **JSON example:** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": [ + "user:eve@example.com" + ], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **YAML example:** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{resource=organizations/*/sources/*}:getIamPolicy", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _GetMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetMuteConfig") + + __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 + } + + def __call__( + self, + request: securitycenter_service.GetMuteConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> mute_config.MuteConfig: + r"""Call the get mute config method over HTTP. + + Args: + request (~.securitycenter_service.GetMuteConfigRequest): + The request object. Request message for retrieving a mute + config. If no location is specified, + default is global. + 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: + ~.mute_config.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=organizations/*/muteConfigs/*}", + }, + { + "method": "get", + "uri": "/v2/{name=organizations/*/locations/*/muteConfigs/*}", + }, + { + "method": "get", + "uri": "/v2/{name=folders/*/muteConfigs/*}", + }, + { + "method": "get", + "uri": "/v2/{name=folders/*/locations/*/muteConfigs/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/muteConfigs/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/muteConfigs/*}", + }, + ] + request, metadata = self._interceptor.pre_get_mute_config(request, metadata) + pb_request = securitycenter_service.GetMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = mute_config.MuteConfig() + pb_resp = mute_config.MuteConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_mute_config(resp) + return resp + + class _GetNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetNotificationConfig") + + __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 + } + + def __call__( + self, + request: securitycenter_service.GetNotificationConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Call the get notification config method over HTTP. + + Args: + request (~.securitycenter_service.GetNotificationConfigRequest): + The request object. Request message for getting a + notification config. + 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: + ~.notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=organizations/*/locations/*/notificationConfigs/*}", + }, + { + "method": "get", + "uri": "/v2/{name=folders/*/locations/*/notificationConfigs/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/notificationConfigs/*}", + }, + ] + request, metadata = self._interceptor.pre_get_notification_config( + request, metadata + ) + pb_request = securitycenter_service.GetNotificationConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = notification_config.NotificationConfig() + pb_resp = notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_notification_config(resp) + return resp + + class _GetResourceValueConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("GetResourceValueConfig") + + __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 + } + + def __call__( + self, + request: securitycenter_service.GetResourceValueConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resource_value_config.ResourceValueConfig: + r"""Call the get resource value config method over HTTP. + + Args: + request (~.securitycenter_service.GetResourceValueConfigRequest): + The request object. Request message to get resource value + config + 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: + ~.resource_value_config.ResourceValueConfig: + A resource value config (RVC) is a + mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=organizations/*/resourceValueConfigs/*}", + }, + ] + request, metadata = self._interceptor.pre_get_resource_value_config( + request, metadata + ) + pb_request = securitycenter_service.GetResourceValueConfigRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = resource_value_config.ResourceValueConfig() + pb_resp = resource_value_config.ResourceValueConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_resource_value_config(resp) + return resp + + class _GetSimulation(SecurityCenterRestStub): + def __hash__(self): + return hash("GetSimulation") + + __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 + } + + def __call__( + self, + request: securitycenter_service.GetSimulationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> simulation.Simulation: + r"""Call the get simulation method over HTTP. + + Args: + request (~.securitycenter_service.GetSimulationRequest): + The request object. Request message for getting + simulation. Simulation name can include + "latest" to retrieve the latest + simulation For example, + "organizations/123/simulations/latest". + 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: + ~.simulation.Simulation: + Attack path simulation + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=organizations/*/simulations/*}", + }, + ] + request, metadata = self._interceptor.pre_get_simulation(request, metadata) + pb_request = securitycenter_service.GetSimulationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = simulation.Simulation() + pb_resp = simulation.Simulation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_simulation(resp) + return resp + + class _GetSource(SecurityCenterRestStub): + def __hash__(self): + return hash("GetSource") + + __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 + } + + def __call__( + self, + request: securitycenter_service.GetSourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Call the get source method over HTTP. + + Args: + request (~.securitycenter_service.GetSourceRequest): + The request object. Request message for getting a source. + 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: + ~.source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=organizations/*/sources/*}", + }, + ] + request, metadata = self._interceptor.pre_get_source(request, metadata) + pb_request = securitycenter_service.GetSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = source.Source() + pb_resp = source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_source(resp) + return resp + + class _GetValuedResource(SecurityCenterRestStub): + def __hash__(self): + return hash("GetValuedResource") + + __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 + } + + def __call__( + self, + request: securitycenter_service.GetValuedResourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> valued_resource.ValuedResource: + r"""Call the get valued resource method over HTTP. + + Args: + request (~.securitycenter_service.GetValuedResourceRequest): + The request object. Request message for getting a valued + resource. + 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: + ~.valued_resource.ValuedResource: + A resource that is determined to have + value to a user's system + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=organizations/*/simulations/*/valuedResources/*}", + }, + ] + request, metadata = self._interceptor.pre_get_valued_resource( + request, metadata + ) + pb_request = securitycenter_service.GetValuedResourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = valued_resource.ValuedResource() + pb_resp = valued_resource.ValuedResource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_valued_resource(resp) + return resp + + class _GroupFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("GroupFindings") + + __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 + } + + def __call__( + self, + request: securitycenter_service.GroupFindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.GroupFindingsResponse: + r"""Call the group findings method over HTTP. + + Args: + request (~.securitycenter_service.GroupFindingsRequest): + The request object. Request message for grouping by + findings. + 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: + ~.securitycenter_service.GroupFindingsResponse: + Response message for group by + findings. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=organizations/*/sources/*}/findings:group", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=organizations/*/sources/*/locations/*}/findings:group", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=folders/*/sources/*}/findings:group", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=folders/*/sources/*/locations/*}/findings:group", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*/sources/*}/findings:group", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*/sources/*/locations/*}/findings:group", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_group_findings(request, metadata) + pb_request = securitycenter_service.GroupFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = securitycenter_service.GroupFindingsResponse() + pb_resp = securitycenter_service.GroupFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_group_findings(resp) + return resp + + class _ListAttackPaths(SecurityCenterRestStub): + def __hash__(self): + return hash("ListAttackPaths") + + __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 + } + + def __call__( + self, + request: securitycenter_service.ListAttackPathsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.ListAttackPathsResponse: + r"""Call the list attack paths method over HTTP. + + Args: + request (~.securitycenter_service.ListAttackPathsRequest): + The request object. Request message for listing the + attack paths for a given simulation or + valued resource. + 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: + ~.securitycenter_service.ListAttackPathsResponse: + Response message for listing the + attack paths for a given simulation or + valued resource. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=organizations/*/simulations/*}/attackPaths", + }, + { + "method": "get", + "uri": "/v2/{parent=organizations/*/simulations/*/valuedResources/*}/attackPaths", + }, + { + "method": "get", + "uri": "/v2/{parent=organizations/*/simulations/*/attackExposureResults/*}/attackPaths", + }, + ] + request, metadata = self._interceptor.pre_list_attack_paths( + request, metadata + ) + pb_request = securitycenter_service.ListAttackPathsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = securitycenter_service.ListAttackPathsResponse() + pb_resp = securitycenter_service.ListAttackPathsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_attack_paths(resp) + return resp + + class _ListBigQueryExports(SecurityCenterRestStub): + def __hash__(self): + return hash("ListBigQueryExports") + + __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 + } + + def __call__( + self, + request: securitycenter_service.ListBigQueryExportsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.ListBigQueryExportsResponse: + r"""Call the list big query exports method over HTTP. + + Args: + request (~.securitycenter_service.ListBigQueryExportsRequest): + The request object. Request message for listing BigQuery + exports at a given scope e.g. + organization, folder or project. + 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: + ~.securitycenter_service.ListBigQueryExportsResponse: + Response message for listing BigQuery + exports. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=organizations/*/locations/*}/bigQueryExports", + }, + { + "method": "get", + "uri": "/v2/{parent=folders/*/locations/*}/bigQueryExports", + }, + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/bigQueryExports", + }, + ] + request, metadata = self._interceptor.pre_list_big_query_exports( + request, metadata + ) + pb_request = securitycenter_service.ListBigQueryExportsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = securitycenter_service.ListBigQueryExportsResponse() + pb_resp = securitycenter_service.ListBigQueryExportsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_big_query_exports(resp) + return resp + + class _ListFindings(SecurityCenterRestStub): + def __hash__(self): + return hash("ListFindings") + + __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 + } + + def __call__( + self, + request: securitycenter_service.ListFindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.ListFindingsResponse: + r"""Call the list findings method over HTTP. + + Args: + request (~.securitycenter_service.ListFindingsRequest): + The request object. Request message for listing findings. + 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: + ~.securitycenter_service.ListFindingsResponse: + Response message for listing + findings. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=organizations/*/sources/*}/findings", + }, + { + "method": "get", + "uri": "/v2/{parent=organizations/*/sources/*/locations/*}/findings", + }, + { + "method": "get", + "uri": "/v2/{parent=folders/*/sources/*}/findings", + }, + { + "method": "get", + "uri": "/v2/{parent=folders/*/sources/*/locations/*}/findings", + }, + { + "method": "get", + "uri": "/v2/{parent=projects/*/sources/*}/findings", + }, + { + "method": "get", + "uri": "/v2/{parent=projects/*/sources/*/locations/*}/findings", + }, + ] + request, metadata = self._interceptor.pre_list_findings(request, metadata) + pb_request = securitycenter_service.ListFindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = securitycenter_service.ListFindingsResponse() + pb_resp = securitycenter_service.ListFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_findings(resp) + return resp + + class _ListMuteConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListMuteConfigs") + + __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 + } + + def __call__( + self, + request: securitycenter_service.ListMuteConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.ListMuteConfigsResponse: + r"""Call the list mute configs method over HTTP. + + Args: + request (~.securitycenter_service.ListMuteConfigsRequest): + The request object. Request message for listing mute + configs at a given scope e.g. + organization, folder or project. If no + location is specified, default is + global. + 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: + ~.securitycenter_service.ListMuteConfigsResponse: + Response message for listing mute + configs. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=organizations/*}/muteConfigs", + }, + { + "method": "get", + "uri": "/v2/{parent=organizations/*/locations/*}/muteConfigs", + }, + { + "method": "get", + "uri": "/v2/{parent=folders/*}/muteConfigs", + }, + { + "method": "get", + "uri": "/v2/{parent=folders/*/locations/*}/muteConfigs", + }, + { + "method": "get", + "uri": "/v2/{parent=projects/*}/muteConfigs", + }, + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/muteConfigs", + }, + ] + request, metadata = self._interceptor.pre_list_mute_configs( + request, metadata + ) + pb_request = securitycenter_service.ListMuteConfigsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = securitycenter_service.ListMuteConfigsResponse() + pb_resp = securitycenter_service.ListMuteConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_mute_configs(resp) + return resp + + class _ListNotificationConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListNotificationConfigs") + + __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 + } + + def __call__( + self, + request: securitycenter_service.ListNotificationConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.ListNotificationConfigsResponse: + r"""Call the list notification configs method over HTTP. + + Args: + request (~.securitycenter_service.ListNotificationConfigsRequest): + The request object. Request message for listing + notification configs. + 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: + ~.securitycenter_service.ListNotificationConfigsResponse: + Response message for listing + notification configs. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=organizations/*/locations/*}/notificationConfigs", + }, + { + "method": "get", + "uri": "/v2/{parent=folders/*/locations/*}/notificationConfigs", + }, + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/notificationConfigs", + }, + ] + request, metadata = self._interceptor.pre_list_notification_configs( + request, metadata + ) + pb_request = securitycenter_service.ListNotificationConfigsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = securitycenter_service.ListNotificationConfigsResponse() + pb_resp = securitycenter_service.ListNotificationConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_notification_configs(resp) + return resp + + class _ListResourceValueConfigs(SecurityCenterRestStub): + def __hash__(self): + return hash("ListResourceValueConfigs") + + __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 + } + + def __call__( + self, + request: securitycenter_service.ListResourceValueConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.ListResourceValueConfigsResponse: + r"""Call the list resource value + configs method over HTTP. + + Args: + request (~.securitycenter_service.ListResourceValueConfigsRequest): + The request object. Request message to list resource + value configs of a parent + 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: + ~.securitycenter_service.ListResourceValueConfigsResponse: + Response message to list resource + value configs + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=organizations/*}/resourceValueConfigs", + }, + ] + request, metadata = self._interceptor.pre_list_resource_value_configs( + request, metadata + ) + pb_request = securitycenter_service.ListResourceValueConfigsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = securitycenter_service.ListResourceValueConfigsResponse() + pb_resp = securitycenter_service.ListResourceValueConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_resource_value_configs(resp) + return resp + + class _ListSources(SecurityCenterRestStub): + def __hash__(self): + return hash("ListSources") + + __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 + } + + def __call__( + self, + request: securitycenter_service.ListSourcesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.ListSourcesResponse: + r"""Call the list sources method over HTTP. + + Args: + request (~.securitycenter_service.ListSourcesRequest): + The request object. Request message for listing sources. + 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: + ~.securitycenter_service.ListSourcesResponse: + Response message for listing sources. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=organizations/*}/sources", + }, + { + "method": "get", + "uri": "/v2/{parent=folders/*}/sources", + }, + { + "method": "get", + "uri": "/v2/{parent=projects/*}/sources", + }, + ] + request, metadata = self._interceptor.pre_list_sources(request, metadata) + pb_request = securitycenter_service.ListSourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = securitycenter_service.ListSourcesResponse() + pb_resp = securitycenter_service.ListSourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_sources(resp) + return resp + + class _ListValuedResources(SecurityCenterRestStub): + def __hash__(self): + return hash("ListValuedResources") + + __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 + } + + def __call__( + self, + request: securitycenter_service.ListValuedResourcesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> securitycenter_service.ListValuedResourcesResponse: + r"""Call the list valued resources method over HTTP. + + Args: + request (~.securitycenter_service.ListValuedResourcesRequest): + The request object. Request message for listing the + valued resources for a given simulation. + 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: + ~.securitycenter_service.ListValuedResourcesResponse: + Response message for listing the + valued resources for a given simulation. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=organizations/*/simulations/*}/valuedResources", + }, + { + "method": "get", + "uri": "/v2/{parent=organizations/*/simulations/*/attackExposureResults/*}/valuedResources", + }, + ] + request, metadata = self._interceptor.pre_list_valued_resources( + request, metadata + ) + pb_request = securitycenter_service.ListValuedResourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = securitycenter_service.ListValuedResourcesResponse() + pb_resp = securitycenter_service.ListValuedResourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_valued_resources(resp) + return resp + + class _SetFindingState(SecurityCenterRestStub): + def __hash__(self): + return hash("SetFindingState") + + __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 + } + + def __call__( + self, + request: securitycenter_service.SetFindingStateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Call the set finding state method over HTTP. + + Args: + request (~.securitycenter_service.SetFindingStateRequest): + The request object. Request message for updating a + finding's state. + 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: + ~.finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=organizations/*/sources/*/findings/*}:setState", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{name=organizations/*/sources/*/locations/*/findings/*}:setState", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{name=folders/*/sources/*/findings/*}:setState", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{name=folders/*/sources/*/locations/*/findings/*}:setState", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{name=projects/*/sources/*/findings/*}:setState", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{name=projects/*/sources/*/locations/*/findings/*}:setState", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_set_finding_state( + request, metadata + ) + pb_request = securitycenter_service.SetFindingStateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = finding.Finding() + pb_resp = finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_finding_state(resp) + return resp + + class _SetIamPolicy(SecurityCenterRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __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 + } + + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (~.iam_policy_pb2.SetIamPolicyRequest): + The request object. Request message for ``SetIamPolicy`` 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: + ~.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **JSON example:** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": [ + "user:eve@example.com" + ], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **YAML example:** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{resource=organizations/*/sources/*}:setIamPolicy", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _SetMute(SecurityCenterRestStub): + def __hash__(self): + return hash("SetMute") + + __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 + } + + def __call__( + self, + request: securitycenter_service.SetMuteRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Call the set mute method over HTTP. + + Args: + request (~.securitycenter_service.SetMuteRequest): + The request object. Request message for updating a + finding's mute status. + 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: + ~.finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=organizations/*/sources/*/findings/*}:setMute", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{name=organizations/*/sources/*/locations/*/findings/*}:setMute", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{name=folders/*/sources/*/findings/*}:setMute", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{name=folders/*/sources/*/locations/*/findings/*}:setMute", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{name=projects/*/sources/*/findings/*}:setMute", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{name=projects/*/sources/*/locations/*/findings/*}:setMute", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_set_mute(request, metadata) + pb_request = securitycenter_service.SetMuteRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = finding.Finding() + pb_resp = finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_mute(resp) + return resp + + class _TestIamPermissions(SecurityCenterRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __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 + } + + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (~.iam_policy_pb2.TestIamPermissionsRequest): + The request object. Request message for ``TestIamPermissions`` 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{resource=organizations/*/sources/*}:testIamPermissions", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + class _UpdateBigQueryExport(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateBigQueryExport") + + __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 + } + + def __call__( + self, + request: securitycenter_service.UpdateBigQueryExportRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> bigquery_export.BigQueryExport: + r"""Call the update big query export method over HTTP. + + Args: + request (~.securitycenter_service.UpdateBigQueryExportRequest): + The request object. Request message for updating a + BigQuery export. + 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: + ~.bigquery_export.BigQueryExport: + Configures how to deliver Findings to + BigQuery Instance. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{big_query_export.name=organizations/*/locations/*/bigQueryExports/*}", + "body": "big_query_export", + }, + { + "method": "patch", + "uri": "/v2/{big_query_export.name=folders/*/locations/*/bigQueryExports/*}", + "body": "big_query_export", + }, + { + "method": "patch", + "uri": "/v2/{big_query_export.name=projects/*/locations/*/bigQueryExports/*}", + "body": "big_query_export", + }, + ] + request, metadata = self._interceptor.pre_update_big_query_export( + request, metadata + ) + pb_request = securitycenter_service.UpdateBigQueryExportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = bigquery_export.BigQueryExport() + pb_resp = bigquery_export.BigQueryExport.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_big_query_export(resp) + return resp + + class _UpdateExternalSystem(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateExternalSystem") + + __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 + } + + def __call__( + self, + request: securitycenter_service.UpdateExternalSystemRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_external_system.ExternalSystem: + r"""Call the update external system method over HTTP. + + Args: + request (~.securitycenter_service.UpdateExternalSystemRequest): + The request object. Request message for updating a + ExternalSystem resource. + 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: + ~.gcs_external_system.ExternalSystem: + Representation of third party + SIEM/SOAR fields within SCC. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}", + "body": "external_system", + }, + { + "method": "patch", + "uri": "/v2/{external_system.name=organizations/*/sources/*/locations/*/findings/*/externalSystems/*}", + "body": "external_system", + }, + { + "method": "patch", + "uri": "/v2/{external_system.name=folders/*/sources/*/findings/*/externalSystems/*}", + "body": "external_system", + }, + { + "method": "patch", + "uri": "/v2/{external_system.name=folders/*/sources/*/locations/*/findings/*/externalSystems/*}", + "body": "external_system", + }, + { + "method": "patch", + "uri": "/v2/{external_system.name=projects/*/sources/*/findings/*/externalSystems/*}", + "body": "external_system", + }, + { + "method": "patch", + "uri": "/v2/{external_system.name=projects/*/sources/*/locations/*/findings/*/externalSystems/*}", + "body": "external_system", + }, + ] + request, metadata = self._interceptor.pre_update_external_system( + request, metadata + ) + pb_request = securitycenter_service.UpdateExternalSystemRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gcs_external_system.ExternalSystem() + pb_resp = gcs_external_system.ExternalSystem.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_external_system(resp) + return resp + + class _UpdateFinding(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateFinding") + + __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 + } + + def __call__( + self, + request: securitycenter_service.UpdateFindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Call the update finding method over HTTP. + + Args: + request (~.securitycenter_service.UpdateFindingRequest): + The request object. Request message for updating or + creating a finding. + 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: + ~.gcs_finding.Finding: + Security Command Center finding. + + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{finding.name=organizations/*/sources/*/findings/*}", + "body": "finding", + }, + { + "method": "patch", + "uri": "/v2/{finding.name=organizations/*/sources/*/locations/*/findings/*}", + "body": "finding", + }, + { + "method": "patch", + "uri": "/v2/{finding.name=folders/*/sources/*/findings/*}", + "body": "finding", + }, + { + "method": "patch", + "uri": "/v2/{finding.name=folders/*/sources/*/locations/*/findings/*}", + "body": "finding", + }, + { + "method": "patch", + "uri": "/v2/{finding.name=projects/*/sources/*/findings/*}", + "body": "finding", + }, + { + "method": "patch", + "uri": "/v2/{finding.name=projects/*/sources/*/locations/*/findings/*}", + "body": "finding", + }, + ] + request, metadata = self._interceptor.pre_update_finding(request, metadata) + pb_request = securitycenter_service.UpdateFindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gcs_finding.Finding() + pb_resp = gcs_finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_finding(resp) + return resp + + class _UpdateMuteConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateMuteConfig") + + __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 + } + + def __call__( + self, + request: securitycenter_service.UpdateMuteConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_mute_config.MuteConfig: + r"""Call the update mute config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateMuteConfigRequest): + The request object. Request message for updating a mute + config. + 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: + ~.gcs_mute_config.MuteConfig: + A mute config is a Cloud SCC resource + that contains the configuration to mute + create/update events of findings. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{mute_config.name=organizations/*/muteConfigs/*}", + "body": "mute_config", + }, + { + "method": "patch", + "uri": "/v2/{mute_config.name=organizations/*/locations/*/muteConfigs/*}", + "body": "mute_config", + }, + { + "method": "patch", + "uri": "/v2/{mute_config.name=folders/*/muteConfigs/*}", + "body": "mute_config", + }, + { + "method": "patch", + "uri": "/v2/{mute_config.name=folders/*/locations/*/muteConfigs/*}", + "body": "mute_config", + }, + { + "method": "patch", + "uri": "/v2/{mute_config.name=projects/*/muteConfigs/*}", + "body": "mute_config", + }, + { + "method": "patch", + "uri": "/v2/{mute_config.name=projects/*/locations/*/muteConfigs/*}", + "body": "mute_config", + }, + ] + request, metadata = self._interceptor.pre_update_mute_config( + request, metadata + ) + pb_request = securitycenter_service.UpdateMuteConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gcs_mute_config.MuteConfig() + pb_resp = gcs_mute_config.MuteConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_mute_config(resp) + return resp + + class _UpdateNotificationConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateNotificationConfig") + + __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 + } + + def __call__( + self, + request: securitycenter_service.UpdateNotificationConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Call the update notification + config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateNotificationConfigRequest): + The request object. Request message for updating a + notification config. + 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: + ~.gcs_notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{notification_config.name=organizations/*/locations/*/notificationConfigs/*}", + "body": "notification_config", + }, + { + "method": "patch", + "uri": "/v2/{notification_config.name=folders/*/locations/*/notificationConfigs/*}", + "body": "notification_config", + }, + { + "method": "patch", + "uri": "/v2/{notification_config.name=projects/*/locations/*/notificationConfigs/*}", + "body": "notification_config", + }, + ] + request, metadata = self._interceptor.pre_update_notification_config( + request, metadata + ) + pb_request = securitycenter_service.UpdateNotificationConfigRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gcs_notification_config.NotificationConfig() + pb_resp = gcs_notification_config.NotificationConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_notification_config(resp) + return resp + + class _UpdateResourceValueConfig(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateResourceValueConfig") + + __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 + } + + def __call__( + self, + request: securitycenter_service.UpdateResourceValueConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_resource_value_config.ResourceValueConfig: + r"""Call the update resource value + config method over HTTP. + + Args: + request (~.securitycenter_service.UpdateResourceValueConfigRequest): + The request object. Request message to update resource + value config + 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: + ~.gcs_resource_value_config.ResourceValueConfig: + A resource value config (RVC) is a + mapping configuration of user's + resources to resource values. Used in + Attack path simulations. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{resource_value_config.name=organizations/*/resourceValueConfigs/*}", + "body": "resource_value_config", + }, + ] + request, metadata = self._interceptor.pre_update_resource_value_config( + request, metadata + ) + pb_request = securitycenter_service.UpdateResourceValueConfigRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gcs_resource_value_config.ResourceValueConfig() + pb_resp = gcs_resource_value_config.ResourceValueConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_resource_value_config(resp) + return resp + + class _UpdateSecurityMarks(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSecurityMarks") + + __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 + } + + def __call__( + self, + request: securitycenter_service.UpdateSecurityMarksRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Call the update security marks method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSecurityMarksRequest): + The request object. Request message for updating a + SecurityMarks resource. + 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: + ~.gcs_security_marks.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}", + "body": "security_marks", + }, + { + "method": "patch", + "uri": "/v2/{security_marks.name=organizations/*/assets/*/securityMarks}", + "body": "security_marks", + }, + { + "method": "patch", + "uri": "/v2/{security_marks.name=organizations/*/sources/*/locations/*/findings/*/securityMarks}", + "body": "security_marks", + }, + { + "method": "patch", + "uri": "/v2/{security_marks.name=folders/*/sources/*/findings/*/securityMarks}", + "body": "security_marks", + }, + { + "method": "patch", + "uri": "/v2/{security_marks.name=folders/*/assets/*/securityMarks}", + "body": "security_marks", + }, + { + "method": "patch", + "uri": "/v2/{security_marks.name=folders/*/sources/*/locations/*/findings/*/securityMarks}", + "body": "security_marks", + }, + { + "method": "patch", + "uri": "/v2/{security_marks.name=projects/*/sources/*/findings/*/securityMarks}", + "body": "security_marks", + }, + { + "method": "patch", + "uri": "/v2/{security_marks.name=projects/*/assets/*/securityMarks}", + "body": "security_marks", + }, + { + "method": "patch", + "uri": "/v2/{security_marks.name=projects/*/sources/*/locations/*/findings/*/securityMarks}", + "body": "security_marks", + }, + ] + request, metadata = self._interceptor.pre_update_security_marks( + request, metadata + ) + pb_request = securitycenter_service.UpdateSecurityMarksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gcs_security_marks.SecurityMarks() + pb_resp = gcs_security_marks.SecurityMarks.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_security_marks(resp) + return resp + + class _UpdateSource(SecurityCenterRestStub): + def __hash__(self): + return hash("UpdateSource") + + __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 + } + + def __call__( + self, + request: securitycenter_service.UpdateSourceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Call the update source method over HTTP. + + Args: + request (~.securitycenter_service.UpdateSourceRequest): + The request object. Request message for updating a + source. + 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: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{source.name=organizations/*/sources/*}", + "body": "source", + }, + ] + request, metadata = self._interceptor.pre_update_source(request, metadata) + pb_request = securitycenter_service.UpdateSourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = gcs_source.Source() + pb_resp = gcs_source.Source.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_source(resp) + return resp + + @property + def batch_create_resource_value_configs( + self, + ) -> Callable[ + [securitycenter_service.BatchCreateResourceValueConfigsRequest], + securitycenter_service.BatchCreateResourceValueConfigsResponse, + ]: + # 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._BatchCreateResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def bulk_mute_findings( + self, + ) -> Callable[ + [securitycenter_service.BulkMuteFindingsRequest], 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._BulkMuteFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_big_query_export( + self, + ) -> Callable[ + [securitycenter_service.CreateBigQueryExportRequest], + bigquery_export.BigQueryExport, + ]: + # 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._CreateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_finding( + self, + ) -> Callable[[securitycenter_service.CreateFindingRequest], gcs_finding.Finding]: + # 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._CreateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_mute_config( + self, + ) -> Callable[ + [securitycenter_service.CreateMuteConfigRequest], gcs_mute_config.MuteConfig + ]: + # 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._CreateMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_notification_config( + self, + ) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig, + ]: + # 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._CreateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_source( + self, + ) -> Callable[[securitycenter_service.CreateSourceRequest], gcs_source.Source]: + # 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._CreateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_big_query_export( + self, + ) -> Callable[ + [securitycenter_service.DeleteBigQueryExportRequest], empty_pb2.Empty + ]: + # 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._DeleteBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_mute_config( + self, + ) -> Callable[[securitycenter_service.DeleteMuteConfigRequest], empty_pb2.Empty]: + # 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._DeleteMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_notification_config( + self, + ) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], empty_pb2.Empty + ]: + # 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._DeleteNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_resource_value_config( + self, + ) -> Callable[ + [securitycenter_service.DeleteResourceValueConfigRequest], empty_pb2.Empty + ]: + # 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._DeleteResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_big_query_export( + self, + ) -> Callable[ + [securitycenter_service.GetBigQueryExportRequest], + bigquery_export.BigQueryExport, + ]: + # 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._GetBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_mute_config( + self, + ) -> Callable[ + [securitycenter_service.GetMuteConfigRequest], mute_config.MuteConfig + ]: + # 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._GetMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_notification_config( + self, + ) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig, + ]: + # 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._GetNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_resource_value_config( + self, + ) -> Callable[ + [securitycenter_service.GetResourceValueConfigRequest], + resource_value_config.ResourceValueConfig, + ]: + # 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._GetResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_simulation( + self, + ) -> Callable[[securitycenter_service.GetSimulationRequest], simulation.Simulation]: + # 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._GetSimulation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_source( + self, + ) -> Callable[[securitycenter_service.GetSourceRequest], source.Source]: + # 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._GetSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_valued_resource( + self, + ) -> Callable[ + [securitycenter_service.GetValuedResourceRequest], + valued_resource.ValuedResource, + ]: + # 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._GetValuedResource(self._session, self._host, self._interceptor) # type: ignore + + @property + def group_findings( + self, + ) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse, + ]: + # 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._GroupFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_attack_paths( + self, + ) -> Callable[ + [securitycenter_service.ListAttackPathsRequest], + securitycenter_service.ListAttackPathsResponse, + ]: + # 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._ListAttackPaths(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_big_query_exports( + self, + ) -> Callable[ + [securitycenter_service.ListBigQueryExportsRequest], + securitycenter_service.ListBigQueryExportsResponse, + ]: + # 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._ListBigQueryExports(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_findings( + self, + ) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.ListFindingsResponse, + ]: + # 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._ListFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_mute_configs( + self, + ) -> Callable[ + [securitycenter_service.ListMuteConfigsRequest], + securitycenter_service.ListMuteConfigsResponse, + ]: + # 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._ListMuteConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_notification_configs( + self, + ) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse, + ]: + # 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._ListNotificationConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_resource_value_configs( + self, + ) -> Callable[ + [securitycenter_service.ListResourceValueConfigsRequest], + securitycenter_service.ListResourceValueConfigsResponse, + ]: + # 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._ListResourceValueConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sources( + self, + ) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse, + ]: + # 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._ListSources(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_valued_resources( + self, + ) -> Callable[ + [securitycenter_service.ListValuedResourcesRequest], + securitycenter_service.ListValuedResourcesResponse, + ]: + # 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._ListValuedResources(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_finding_state( + self, + ) -> Callable[[securitycenter_service.SetFindingStateRequest], finding.Finding]: + # 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._SetFindingState(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_mute( + self, + ) -> Callable[[securitycenter_service.SetMuteRequest], finding.Finding]: + # 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._SetMute(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_big_query_export( + self, + ) -> Callable[ + [securitycenter_service.UpdateBigQueryExportRequest], + bigquery_export.BigQueryExport, + ]: + # 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._UpdateBigQueryExport(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_external_system( + self, + ) -> Callable[ + [securitycenter_service.UpdateExternalSystemRequest], + gcs_external_system.ExternalSystem, + ]: + # 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._UpdateExternalSystem(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_finding( + self, + ) -> Callable[[securitycenter_service.UpdateFindingRequest], gcs_finding.Finding]: + # 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._UpdateFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_mute_config( + self, + ) -> Callable[ + [securitycenter_service.UpdateMuteConfigRequest], gcs_mute_config.MuteConfig + ]: + # 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._UpdateMuteConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_notification_config( + self, + ) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig, + ]: + # 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._UpdateNotificationConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_resource_value_config( + self, + ) -> Callable[ + [securitycenter_service.UpdateResourceValueConfigRequest], + gcs_resource_value_config.ResourceValueConfig, + ]: + # 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._UpdateResourceValueConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_security_marks( + self, + ) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks, + ]: + # 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._UpdateSecurityMarks(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_source( + self, + ) -> Callable[[securitycenter_service.UpdateSourceRequest], gcs_source.Source]: + # 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._UpdateSource(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(SecurityCenterRestStub): + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=organizations/*/operations/*}:cancel", + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # 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 self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(SecurityCenterRestStub): + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=organizations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # 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 self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(SecurityCenterRestStub): + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation 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: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=organizations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(SecurityCenterRestStub): + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations 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.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=organizations/*/operations}", + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("SecurityCenterRestTransport",) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/__init__.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/__init__.py new file mode 100644 index 000000000000..0706730e171e --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/__init__.py @@ -0,0 +1,216 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 .access import Access, Geolocation, ServiceAccountDelegationInfo +from .application import Application +from .attack_exposure import AttackExposure +from .attack_path import AttackPath +from .backup_disaster_recovery import BackupDisasterRecovery +from .bigquery_export import BigQueryExport +from .cloud_dlp_data_profile import CloudDlpDataProfile +from .cloud_dlp_inspection import CloudDlpInspection +from .compliance import Compliance +from .connection import Connection +from .contact_details import Contact, ContactDetails +from .container import Container +from .database import Database +from .exfiltration import ExfilResource, Exfiltration +from .external_system import ExternalSystem +from .file import File +from .finding import Finding +from .iam_binding import IamBinding +from .indicator import Indicator +from .kernel_rootkit import KernelRootkit +from .kubernetes import Kubernetes +from .label import Label +from .load_balancer import LoadBalancer +from .log_entry import CloudLoggingEntry, LogEntry +from .mitre_attack import MitreAttack +from .mute_config import MuteConfig +from .notification_config import NotificationConfig +from .notification_message import NotificationMessage +from .org_policy import OrgPolicy +from .process import EnvironmentVariable, Process +from .resource import Resource +from .resource_value_config import ResourceValue, ResourceValueConfig +from .security_marks import SecurityMarks +from .security_posture import SecurityPosture +from .securitycenter_service import ( + BatchCreateResourceValueConfigsRequest, + BatchCreateResourceValueConfigsResponse, + BulkMuteFindingsRequest, + BulkMuteFindingsResponse, + CreateBigQueryExportRequest, + CreateFindingRequest, + CreateMuteConfigRequest, + CreateNotificationConfigRequest, + CreateResourceValueConfigRequest, + CreateSourceRequest, + DeleteBigQueryExportRequest, + DeleteMuteConfigRequest, + DeleteNotificationConfigRequest, + DeleteResourceValueConfigRequest, + GetBigQueryExportRequest, + GetMuteConfigRequest, + GetNotificationConfigRequest, + GetResourceValueConfigRequest, + GetSimulationRequest, + GetSourceRequest, + GetValuedResourceRequest, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListAttackPathsRequest, + ListAttackPathsResponse, + ListBigQueryExportsRequest, + ListBigQueryExportsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListMuteConfigsRequest, + ListMuteConfigsResponse, + ListNotificationConfigsRequest, + ListNotificationConfigsResponse, + ListResourceValueConfigsRequest, + ListResourceValueConfigsResponse, + ListSourcesRequest, + ListSourcesResponse, + ListValuedResourcesRequest, + ListValuedResourcesResponse, + SetFindingStateRequest, + SetMuteRequest, + UpdateBigQueryExportRequest, + UpdateExternalSystemRequest, + UpdateFindingRequest, + UpdateMuteConfigRequest, + UpdateNotificationConfigRequest, + UpdateResourceValueConfigRequest, + UpdateSecurityMarksRequest, + UpdateSourceRequest, +) +from .simulation import Simulation +from .source import Source +from .valued_resource import ResourceValueConfigMetadata, ValuedResource +from .vulnerability import ( + Cve, + Cvssv3, + Package, + Reference, + SecurityBulletin, + Vulnerability, +) + +__all__ = ( + "Access", + "Geolocation", + "ServiceAccountDelegationInfo", + "Application", + "AttackExposure", + "AttackPath", + "BackupDisasterRecovery", + "BigQueryExport", + "CloudDlpDataProfile", + "CloudDlpInspection", + "Compliance", + "Connection", + "Contact", + "ContactDetails", + "Container", + "Database", + "ExfilResource", + "Exfiltration", + "ExternalSystem", + "File", + "Finding", + "IamBinding", + "Indicator", + "KernelRootkit", + "Kubernetes", + "Label", + "LoadBalancer", + "CloudLoggingEntry", + "LogEntry", + "MitreAttack", + "MuteConfig", + "NotificationConfig", + "NotificationMessage", + "OrgPolicy", + "EnvironmentVariable", + "Process", + "Resource", + "ResourceValueConfig", + "ResourceValue", + "SecurityMarks", + "SecurityPosture", + "BatchCreateResourceValueConfigsRequest", + "BatchCreateResourceValueConfigsResponse", + "BulkMuteFindingsRequest", + "BulkMuteFindingsResponse", + "CreateBigQueryExportRequest", + "CreateFindingRequest", + "CreateMuteConfigRequest", + "CreateNotificationConfigRequest", + "CreateResourceValueConfigRequest", + "CreateSourceRequest", + "DeleteBigQueryExportRequest", + "DeleteMuteConfigRequest", + "DeleteNotificationConfigRequest", + "DeleteResourceValueConfigRequest", + "GetBigQueryExportRequest", + "GetMuteConfigRequest", + "GetNotificationConfigRequest", + "GetResourceValueConfigRequest", + "GetSimulationRequest", + "GetSourceRequest", + "GetValuedResourceRequest", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "ListAttackPathsRequest", + "ListAttackPathsResponse", + "ListBigQueryExportsRequest", + "ListBigQueryExportsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "ListMuteConfigsRequest", + "ListMuteConfigsResponse", + "ListNotificationConfigsRequest", + "ListNotificationConfigsResponse", + "ListResourceValueConfigsRequest", + "ListResourceValueConfigsResponse", + "ListSourcesRequest", + "ListSourcesResponse", + "ListValuedResourcesRequest", + "ListValuedResourcesResponse", + "SetFindingStateRequest", + "SetMuteRequest", + "UpdateBigQueryExportRequest", + "UpdateExternalSystemRequest", + "UpdateFindingRequest", + "UpdateMuteConfigRequest", + "UpdateNotificationConfigRequest", + "UpdateResourceValueConfigRequest", + "UpdateSecurityMarksRequest", + "UpdateSourceRequest", + "Simulation", + "Source", + "ResourceValueConfigMetadata", + "ValuedResource", + "Cve", + "Cvssv3", + "Package", + "Reference", + "SecurityBulletin", + "Vulnerability", +) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/access.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/access.py new file mode 100644 index 000000000000..418ca6b034ae --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/access.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "Access", + "ServiceAccountDelegationInfo", + "Geolocation", + }, +) + + +class Access(proto.Message): + r"""Represents an access event. + + Attributes: + principal_email (str): + Associated email, such as "foo@google.com". + + The email address of the authenticated user or a service + account acting on behalf of a third party principal making + the request. For third party identity callers, the + ``principal_subject`` field is populated instead of this + field. For privacy reasons, the principal email address is + sometimes redacted. For more information, see `Caller + identities in audit + logs `__. + caller_ip (str): + Caller's IP address, such as "1.1.1.1". + caller_ip_geo (google.cloud.securitycenter_v2.types.Geolocation): + The caller IP's geolocation, which identifies + where the call came from. + user_agent_family (str): + Type of user agent associated with the + finding. For example, an operating system shell + or an embedded or standalone application. + user_agent (str): + The caller's user agent string associated + with the finding. + service_name (str): + This is the API service that the service + account made a call to, e.g. + "iam.googleapis.com". + method_name (str): + The method that the service account called, + e.g. "SetIamPolicy". + principal_subject (str): + A string that represents the principal_subject that is + associated with the identity. Unlike ``principal_email``, + ``principal_subject`` supports principals that aren't + associated with email addresses, such as third party + principals. For most identities, the format is + ``principal://iam.googleapis.com/{identity pool name}/subject/{subject}``. + Some GKE identities, such as GKE_WORKLOAD, FREEFORM, and + GKE_HUB_WORKLOAD, still use the legacy format + ``serviceAccount:{identity pool name}[{subject}]``. + service_account_key_name (str): + The name of the service account key that was used to create + or exchange credentials when authenticating the service + account that made the request. This is a scheme-less URI + full resource name. For example: + + "//iam.googleapis.com/projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}". + service_account_delegation_info (MutableSequence[google.cloud.securitycenter_v2.types.ServiceAccountDelegationInfo]): + The identity delegation history of an authenticated service + account that made the request. The + ``serviceAccountDelegationInfo[]`` object contains + information about the real authorities that try to access + Google Cloud resources by delegating on a service account. + When multiple authorities are present, they are guaranteed + to be sorted based on the original ordering of the identity + delegation events. + user_name (str): + A string that represents a username. The + username provided depends on the type of the + finding and is likely not an IAM principal. For + example, this can be a system username if the + finding is related to a virtual machine, or it + can be an application login username. + """ + + principal_email: str = proto.Field( + proto.STRING, + number=1, + ) + caller_ip: str = proto.Field( + proto.STRING, + number=2, + ) + caller_ip_geo: "Geolocation" = proto.Field( + proto.MESSAGE, + number=3, + message="Geolocation", + ) + user_agent_family: str = proto.Field( + proto.STRING, + number=4, + ) + user_agent: str = proto.Field( + proto.STRING, + number=5, + ) + service_name: str = proto.Field( + proto.STRING, + number=6, + ) + method_name: str = proto.Field( + proto.STRING, + number=7, + ) + principal_subject: str = proto.Field( + proto.STRING, + number=8, + ) + service_account_key_name: str = proto.Field( + proto.STRING, + number=9, + ) + service_account_delegation_info: MutableSequence[ + "ServiceAccountDelegationInfo" + ] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message="ServiceAccountDelegationInfo", + ) + user_name: str = proto.Field( + proto.STRING, + number=11, + ) + + +class ServiceAccountDelegationInfo(proto.Message): + r"""Identity delegation history of an authenticated service + account. + + Attributes: + principal_email (str): + The email address of a Google account. + principal_subject (str): + A string representing the principal_subject associated with + the identity. As compared to ``principal_email``, supports + principals that aren't associated with email addresses, such + as third party principals. For most identities, the format + will be + ``principal://iam.googleapis.com/{identity pool name}/subjects/{subject}`` + except for some GKE identities (GKE_WORKLOAD, FREEFORM, + GKE_HUB_WORKLOAD) that are still in the legacy format + ``serviceAccount:{identity pool name}[{subject}]`` + """ + + principal_email: str = proto.Field( + proto.STRING, + number=1, + ) + principal_subject: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Geolocation(proto.Message): + r"""Represents a geographical location for a given access. + + Attributes: + region_code (str): + A CLDR. + """ + + region_code: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/application.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/application.py new file mode 100644 index 000000000000..7a6748ca0e1c --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/application.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "Application", + }, +) + + +class Application(proto.Message): + r"""Represents an application associated with a finding. + + Attributes: + base_uri (str): + The base URI that identifies the network location of the + application in which the vulnerability was detected. For + example, ``http://example.com``. + full_uri (str): + The full URI with payload that could be used to reproduce + the vulnerability. For example, + ``http://example.com?p=aMmYgI6H``. + """ + + base_uri: str = proto.Field( + proto.STRING, + number=1, + ) + full_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/attack_exposure.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/attack_exposure.py new file mode 100644 index 000000000000..2898db419f1e --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/attack_exposure.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "AttackExposure", + }, +) + + +class AttackExposure(proto.Message): + r"""An attack exposure contains the results of an attack path + simulation run. + + Attributes: + score (float): + A number between 0 (inclusive) and infinity + that represents how important this finding is to + remediate. The higher the score, the more + important it is to remediate. + latest_calculation_time (google.protobuf.timestamp_pb2.Timestamp): + The most recent time the attack exposure was + updated on this finding. + attack_exposure_result (str): + The resource name of the attack path + simulation result that contains the details + regarding this attack exposure score. Example: + organizations/123/simulations/456/attackExposureResults/789 + state (google.cloud.securitycenter_v2.types.AttackExposure.State): + Output only. What state this AttackExposure + is in. This captures whether or not an attack + exposure has been calculated or not. + exposed_high_value_resources_count (int): + The number of high value resources that are + exposed as a result of this finding. + exposed_medium_value_resources_count (int): + The number of medium value resources that are + exposed as a result of this finding. + exposed_low_value_resources_count (int): + The number of high value resources that are + exposed as a result of this finding. + """ + + class State(proto.Enum): + r"""This enum defines the various states an AttackExposure can be + in. + + Values: + STATE_UNSPECIFIED (0): + The state is not specified. + CALCULATED (1): + The attack exposure has been calculated. + NOT_CALCULATED (2): + The attack exposure has not been calculated. + """ + STATE_UNSPECIFIED = 0 + CALCULATED = 1 + NOT_CALCULATED = 2 + + score: float = proto.Field( + proto.DOUBLE, + number=1, + ) + latest_calculation_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + attack_exposure_result: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + exposed_high_value_resources_count: int = proto.Field( + proto.INT32, + number=5, + ) + exposed_medium_value_resources_count: int = proto.Field( + proto.INT32, + number=6, + ) + exposed_low_value_resources_count: int = proto.Field( + proto.INT32, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/attack_path.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/attack_path.py new file mode 100644 index 000000000000..e135432c52fd --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/attack_path.py @@ -0,0 +1,228 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "AttackPath", + }, +) + + +class AttackPath(proto.Message): + r"""A path that an attacker could take to reach an exposed + resource. + + Attributes: + name (str): + The attack path name, for example, + ``organizations/12/simulations/34/valuedResources/56/attackPaths/78`` + path_nodes (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode]): + A list of nodes that exist in this attack + path. + edges (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathEdge]): + A list of the edges between nodes in this + attack path. + """ + + class AttackPathNode(proto.Message): + r"""Represents one point that an attacker passes through in this + attack path. + + Attributes: + resource (str): + The name of the resource at this point in the attack path. + The format of the name follows the Cloud Asset Inventory + `resource name + format <"https://cloud.google.com/asset-inventory/docs/resource-name-format">`__ + resource_type (str): + The `supported resource + type `__ + display_name (str): + Human-readable name of this resource. + associated_findings (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode.PathNodeAssociatedFinding]): + The findings associated with this node in the + attack path. + uuid (str): + Unique id of the attack path node. + attack_steps (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode.AttackStepNode]): + A list of attack step nodes that exist in + this attack path node. + """ + + class NodeType(proto.Enum): + r"""The type of the incoming attack step node. + + Values: + NODE_TYPE_UNSPECIFIED (0): + Type not specified + NODE_TYPE_AND (1): + Incoming edge joined with AND + NODE_TYPE_OR (2): + Incoming edge joined with OR + NODE_TYPE_DEFENSE (3): + Incoming edge is defense + NODE_TYPE_ATTACKER (4): + Incoming edge is attacker + """ + NODE_TYPE_UNSPECIFIED = 0 + NODE_TYPE_AND = 1 + NODE_TYPE_OR = 2 + NODE_TYPE_DEFENSE = 3 + NODE_TYPE_ATTACKER = 4 + + class PathNodeAssociatedFinding(proto.Message): + r"""A finding that is associated with this node in the attack + path. + + Attributes: + canonical_finding (str): + Canonical name of the associated findings. + Example: + organizations/123/sources/456/findings/789 + finding_category (str): + The additional taxonomy group within findings + from a given source. + name (str): + Full resource name of the finding. + """ + + canonical_finding: str = proto.Field( + proto.STRING, + number=1, + ) + finding_category: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + class AttackStepNode(proto.Message): + r"""Detailed steps the attack can take between path nodes. + + Attributes: + uuid (str): + Unique ID for one Node + type_ (google.cloud.securitycenter_v2.types.AttackPath.AttackPathNode.NodeType): + Attack step type. Can be either AND, OR or + DEFENSE + display_name (str): + User friendly name of the attack step + labels (MutableMapping[str, str]): + Attack step labels for metadata + description (str): + Attack step description + """ + + uuid: str = proto.Field( + proto.STRING, + number=1, + ) + type_: "AttackPath.AttackPathNode.NodeType" = proto.Field( + proto.ENUM, + number=2, + enum="AttackPath.AttackPathNode.NodeType", + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + + resource: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + associated_findings: MutableSequence[ + "AttackPath.AttackPathNode.PathNodeAssociatedFinding" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="AttackPath.AttackPathNode.PathNodeAssociatedFinding", + ) + uuid: str = proto.Field( + proto.STRING, + number=5, + ) + attack_steps: MutableSequence[ + "AttackPath.AttackPathNode.AttackStepNode" + ] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message="AttackPath.AttackPathNode.AttackStepNode", + ) + + class AttackPathEdge(proto.Message): + r"""Represents a connection between a source node and a + destination node in this attack path. + + Attributes: + source (str): + The attack node uuid of the source node. + destination (str): + The attack node uuid of the destination node. + """ + + source: str = proto.Field( + proto.STRING, + number=1, + ) + destination: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + path_nodes: MutableSequence[AttackPathNode] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=AttackPathNode, + ) + edges: MutableSequence[AttackPathEdge] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=AttackPathEdge, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py new file mode 100644 index 000000000000..030737124c9d --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/backup_disaster_recovery.py @@ -0,0 +1,135 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "BackupDisasterRecovery", + }, +) + + +class BackupDisasterRecovery(proto.Message): + r"""Information related to Google Cloud Backup and DR Service + findings. + + Attributes: + backup_template (str): + The name of a Backup and DR template which comprises one or + more backup policies. See the `Backup and DR + documentation `__ + for more information. For example, ``snap-ov``. + policies (MutableSequence[str]): + The names of Backup and DR policies that are associated with + a template and that define when to run a backup, how + frequently to run a backup, and how long to retain the + backup image. For example, ``onvaults``. + host (str): + The name of a Backup and DR host, which is managed by the + backup and recovery appliance and known to the management + console. The host can be of type Generic (for example, + Compute Engine, SQL Server, Oracle DB, SMB file system, + etc.), vCenter, or an ESX server. See the `Backup and DR + documentation on + hosts `__ + for more information. For example, ``centos7-01``. + applications (MutableSequence[str]): + The names of Backup and DR applications. An application is a + VM, database, or file system on a managed host monitored by + a backup and recovery appliance. For example, + ``centos7-01-vol00``, ``centos7-01-vol01``, + ``centos7-01-vol02``. + storage_pool (str): + The name of the Backup and DR storage pool that the backup + and recovery appliance is storing data in. The storage pool + could be of type Cloud, Primary, Snapshot, or OnVault. See + the `Backup and DR documentation on storage + pools `__. + For example, ``DiskPoolOne``. + policy_options (MutableSequence[str]): + The names of Backup and DR advanced policy options of a + policy applying to an application. See the `Backup and DR + documentation on policy + options `__. + For example, ``skipofflineappsincongrp, nounmap``. + profile (str): + The name of the Backup and DR resource profile that + specifies the storage media for backups of application and + VM data. See the `Backup and DR documentation on + profiles `__. + For example, ``GCP``. + appliance (str): + The name of the Backup and DR appliance that captures, + moves, and manages the lifecycle of backup data. For + example, ``backup-server-57137``. + backup_type (str): + The backup type of the Backup and DR image. For example, + ``Snapshot``, ``Remote Snapshot``, ``OnVault``. + backup_create_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp at which the Backup and DR + backup was created. + """ + + backup_template: str = proto.Field( + proto.STRING, + number=1, + ) + policies: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + host: str = proto.Field( + proto.STRING, + number=3, + ) + applications: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + storage_pool: str = proto.Field( + proto.STRING, + number=5, + ) + policy_options: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + profile: str = proto.Field( + proto.STRING, + number=7, + ) + appliance: str = proto.Field( + proto.STRING, + number=8, + ) + backup_type: str = proto.Field( + proto.STRING, + number=9, + ) + backup_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/bigquery_export.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/bigquery_export.py new file mode 100644 index 000000000000..d935d7b328fa --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/bigquery_export.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "BigQueryExport", + }, +) + + +class BigQueryExport(proto.Message): + r"""Configures how to deliver Findings to BigQuery Instance. + + Attributes: + name (str): + The relative resource name of this export. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name. + The following list shows some examples: + + - + + ``organizations/{organization_id}/locations/{location_id}/bigQueryExports/{export_id}`` + + - ``folders/{folder_id}/locations/{location_id}/bigQueryExports/{export_id}`` + - + + ``projects/{project_id}/locations/{location_id}/bigQueryExports/{export_id}`` + + This field is provided in responses, and is ignored when + provided in create requests. + description (str): + The description of the export (max of 1024 + characters). + filter (str): + Expression that defines the filter to apply across + create/update events of findings. The expression is a list + of zero or more restrictions combined via logical operators + ``AND`` and ``OR``. Parentheses are supported, and ``OR`` + has higher precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + dataset (str): + The dataset to write findings' updates to. Its format is + "projects/[project_id]/datasets/[bigquery_dataset_id]". + BigQuery Dataset unique ID must contain only letters (a-z, + A-Z), numbers (0-9), or underscores (_). + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the BigQuery + export was created. This field is set by the + server and will be ignored if provided on export + on creation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time at which + the BigQuery export was updated. This field is + set by the server and will be ignored if + provided on export creation or update. + most_recent_editor (str): + Output only. Email address of the user who + last edited the BigQuery export. This field is + set by the server and will be ignored if + provided on export creation or update. + principal (str): + Output only. The service account that needs + permission to create table and upload data to + the BigQuery dataset. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + dataset: str = proto.Field( + proto.STRING, + number=4, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + most_recent_editor: str = proto.Field( + proto.STRING, + number=7, + ) + principal: str = proto.Field( + proto.STRING, + number=8, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.py new file mode 100644 index 000000000000..52f9e4b253a0 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/cloud_dlp_data_profile.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "CloudDlpDataProfile", + }, +) + + +class CloudDlpDataProfile(proto.Message): + r"""The `data + profile `__ + associated with the finding. + + Attributes: + data_profile (str): + Name of the data profile, for example, + ``projects/123/locations/europe/tableProfiles/8383929``. + parent_type (google.cloud.securitycenter_v2.types.CloudDlpDataProfile.ParentType): + The resource hierarchy level at which the + data profile was generated. + """ + + class ParentType(proto.Enum): + r"""Parents for configurations that produce data profile + findings. + + Values: + PARENT_TYPE_UNSPECIFIED (0): + Unspecified parent type. + ORGANIZATION (1): + Organization-level configurations. + PROJECT (2): + Project-level configurations. + """ + PARENT_TYPE_UNSPECIFIED = 0 + ORGANIZATION = 1 + PROJECT = 2 + + data_profile: str = proto.Field( + proto.STRING, + number=1, + ) + parent_type: ParentType = proto.Field( + proto.ENUM, + number=2, + enum=ParentType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.py new file mode 100644 index 000000000000..bb19bcf8fda1 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/cloud_dlp_inspection.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "CloudDlpInspection", + }, +) + + +class CloudDlpInspection(proto.Message): + r"""Details about the Cloud Data Loss Prevention (Cloud DLP) `inspection + job `__ + that produced the finding. + + Attributes: + inspect_job (str): + Name of the inspection job, for example, + ``projects/123/locations/europe/dlpJobs/i-8383929``. + info_type (str): + The type of information (or + `infoType `__) + found, for example, ``EMAIL_ADDRESS`` or ``STREET_ADDRESS``. + info_type_count (int): + The number of times Cloud DLP found this + infoType within this job and resource. + full_scan (bool): + Whether Cloud DLP scanned the complete + resource or a sampled subset. + """ + + inspect_job: str = proto.Field( + proto.STRING, + number=1, + ) + info_type: str = proto.Field( + proto.STRING, + number=2, + ) + info_type_count: int = proto.Field( + proto.INT64, + number=3, + ) + full_scan: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/compliance.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/compliance.py new file mode 100644 index 000000000000..7b0445ed2401 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/compliance.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "Compliance", + }, +) + + +class Compliance(proto.Message): + r"""Contains compliance information about a security standard + indicating unmet recommendations. + + Attributes: + standard (str): + Industry-wide compliance standards or + benchmarks, such as CIS, PCI, and OWASP. + version (str): + Version of the standard or benchmark, for + example, 1.1 + ids (MutableSequence[str]): + Policies within the standard or benchmark, + for example, A.12.4.1 + """ + + standard: str = proto.Field( + proto.STRING, + number=1, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/connection.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/connection.py new file mode 100644 index 000000000000..d95619f1946f --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/connection.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "Connection", + }, +) + + +class Connection(proto.Message): + r"""Contains information about the IP connection associated with + the finding. + + Attributes: + destination_ip (str): + Destination IP address. Not present for + sockets that are listening and not connected. + destination_port (int): + Destination port. Not present for sockets + that are listening and not connected. + source_ip (str): + Source IP address. + source_port (int): + Source port. + protocol (google.cloud.securitycenter_v2.types.Connection.Protocol): + IANA Internet Protocol Number such as TCP(6) + and UDP(17). + """ + + class Protocol(proto.Enum): + r"""IANA Internet Protocol Number such as TCP(6) and UDP(17). + + Values: + PROTOCOL_UNSPECIFIED (0): + Unspecified protocol (not HOPOPT). + ICMP (1): + Internet Control Message Protocol. + TCP (6): + Transmission Control Protocol. + UDP (17): + User Datagram Protocol. + GRE (47): + Generic Routing Encapsulation. + ESP (50): + Encap Security Payload. + """ + PROTOCOL_UNSPECIFIED = 0 + ICMP = 1 + TCP = 6 + UDP = 17 + GRE = 47 + ESP = 50 + + destination_ip: str = proto.Field( + proto.STRING, + number=1, + ) + destination_port: int = proto.Field( + proto.INT32, + number=2, + ) + source_ip: str = proto.Field( + proto.STRING, + number=3, + ) + source_port: int = proto.Field( + proto.INT32, + number=4, + ) + protocol: Protocol = proto.Field( + proto.ENUM, + number=5, + enum=Protocol, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/contact_details.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/contact_details.py new file mode 100644 index 000000000000..43479810fcd8 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/contact_details.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "ContactDetails", + "Contact", + }, +) + + +class ContactDetails(proto.Message): + r"""Details about specific contacts + + Attributes: + contacts (MutableSequence[google.cloud.securitycenter_v2.types.Contact]): + A list of contacts + """ + + contacts: MutableSequence["Contact"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Contact", + ) + + +class Contact(proto.Message): + r"""The email address of a contact. + + Attributes: + email (str): + An email address. For example, "``person123@company.com``". + """ + + email: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/container.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/container.py new file mode 100644 index 000000000000..a9c057dfec3d --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/container.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter_v2.types import label + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v2", + manifest={ + "Container", + }, +) + + +class Container(proto.Message): + r"""Container associated with the finding. + + Attributes: + name (str): + Name of the container. + uri (str): + Container image URI provided when configuring + a pod or container. This string can identify a + container image version using mutable tags. + image_id (str): + Optional container image ID, if provided by + the container runtime. Uniquely identifies the + container image launched using a container image + digest. + labels (MutableSequence[google.cloud.securitycenter_v2.types.Label]): + Container labels, as provided by the + container runtime. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time that the container was created. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + image_id: str = proto.Field( + proto.STRING, + number=3, + ) + labels: MutableSequence[label.Label] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=label.Label, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/database.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/database.py new file mode 100644 index 000000000000..c6e72495b397 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/database.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "Database", + }, +) + + +class Database(proto.Message): + r"""Represents database access information, such as queries. A database + may be a sub-resource of an instance (as in the case of Cloud SQL + instances or Cloud Spanner instances), or the database instance + itself. Some database resources might not have the `full resource + name `__ populated + because these resource types, such as Cloud SQL databases, are not + yet supported by Cloud Asset Inventory. In these cases only the + display name is provided. + + Attributes: + name (str): + Some database resources may not have the `full resource + name `__ + populated because these resource types are not yet supported + by Cloud Asset Inventory (e.g. Cloud SQL databases). In + these cases only the display name will be provided. The + `full resource + name `__ of + the database that the user connected to, if it is supported + by Cloud Asset Inventory. + display_name (str): + The human-readable name of the database that + the user connected to. + user_name (str): + The username used to connect to the database. + The username might not be an IAM principal and + does not have a set format. + query (str): + The SQL statement that is associated with the + database access. + grantees (MutableSequence[str]): + The target usernames, roles, or groups of an + SQL privilege grant, which is not an IAM policy + change. + version (str): + The version of the database, for example, POSTGRES_14. See + `the complete + list `__. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + user_name: str = proto.Field( + proto.STRING, + number=3, + ) + query: str = proto.Field( + proto.STRING, + number=4, + ) + grantees: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + version: str = proto.Field( + proto.STRING, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/exfiltration.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/exfiltration.py new file mode 100644 index 000000000000..14f08452b2d2 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/exfiltration.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "Exfiltration", + "ExfilResource", + }, +) + + +class Exfiltration(proto.Message): + r"""Exfiltration represents a data exfiltration attempt from one or more + sources to one or more targets. The ``sources`` attribute lists the + sources of the exfiltrated data. The ``targets`` attribute lists the + destinations the data was copied to. + + Attributes: + sources (MutableSequence[google.cloud.securitycenter_v2.types.ExfilResource]): + If there are multiple sources, then the data + is considered "joined" between them. For + instance, BigQuery can join multiple tables, and + each table would be considered a source. + targets (MutableSequence[google.cloud.securitycenter_v2.types.ExfilResource]): + If there are multiple targets, each target + would get a complete copy of the "joined" source + data. + total_exfiltrated_bytes (int): + Total exfiltrated bytes processed for the + entire job. + """ + + sources: MutableSequence["ExfilResource"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ExfilResource", + ) + targets: MutableSequence["ExfilResource"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="ExfilResource", + ) + total_exfiltrated_bytes: int = proto.Field( + proto.INT64, + number=3, + ) + + +class ExfilResource(proto.Message): + r"""Resource where data was exfiltrated from or exfiltrated to. + + Attributes: + name (str): + The resource's `full resource + name `__. + components (MutableSequence[str]): + Subcomponents of the asset that was + exfiltrated, like URIs used during exfiltration, + table names, databases, and filenames. For + example, multiple tables might have been + exfiltrated from the same Cloud SQL instance, or + multiple files might have been exfiltrated from + the same Cloud Storage bucket. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + components: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/external_system.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/external_system.py new file mode 100644 index 000000000000..e6e763323267 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/external_system.py @@ -0,0 +1,190 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "ExternalSystem", + }, +) + + +class ExternalSystem(proto.Message): + r"""Representation of third party SIEM/SOAR fields within SCC. + + Attributes: + name (str): + Full resource name of the external system. The following + list shows some examples: + + - ``organizations/1234/sources/5678/findings/123456/externalSystems/jira`` + - + + ``organizations/1234/sources/5678/locations/us/findings/123456/externalSystems/jira`` + + - ``folders/1234/sources/5678/findings/123456/externalSystems/jira`` + - + + ``folders/1234/sources/5678/locations/us/findings/123456/externalSystems/jira`` + + - ``projects/1234/sources/5678/findings/123456/externalSystems/jira`` + - + + ``projects/1234/sources/5678/locations/us/findings/123456/externalSystems/jira`` + assignees (MutableSequence[str]): + References primary/secondary etc assignees in + the external system. + external_uid (str): + The identifier that's used to track the + finding's corresponding case in the external + system. + status (str): + The most recent status of the finding's + corresponding case, as reported by the external + system. + external_system_update_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the case was last updated, as + reported by the external system. + case_uri (str): + The link to the finding's corresponding case + in the external system. + case_priority (str): + The priority of the finding's corresponding + case in the external system. + case_sla (google.protobuf.timestamp_pb2.Timestamp): + The SLA of the finding's corresponding case + in the external system. + case_create_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the case was created, as + reported by the external system. + case_close_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the case was closed, as + reported by the external system. + ticket_info (google.cloud.securitycenter_v2.types.ExternalSystem.TicketInfo): + Information about the ticket, if any, that is + being used to track the resolution of the issue + that is identified by this finding. + """ + + class TicketInfo(proto.Message): + r"""Information about the ticket, if any, that is being used to + track the resolution of the issue that is identified by this + finding. + + Attributes: + id (str): + The identifier of the ticket in the ticket + system. + assignee (str): + The assignee of the ticket in the ticket + system. + description (str): + The description of the ticket in the ticket + system. + uri (str): + The link to the ticket in the ticket system. + status (str): + The latest status of the ticket, as reported + by the ticket system. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the ticket was last updated, as + reported by the ticket system. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + assignee: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + uri: str = proto.Field( + proto.STRING, + number=4, + ) + status: str = proto.Field( + proto.STRING, + number=5, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + assignees: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + external_uid: str = proto.Field( + proto.STRING, + number=3, + ) + status: str = proto.Field( + proto.STRING, + number=4, + ) + external_system_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + case_uri: str = proto.Field( + proto.STRING, + number=6, + ) + case_priority: str = proto.Field( + proto.STRING, + number=7, + ) + case_sla: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + case_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + case_close_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + ticket_info: TicketInfo = proto.Field( + proto.MESSAGE, + number=8, + message=TicketInfo, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/file.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/file.py new file mode 100644 index 000000000000..b68b00daead0 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/file.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "File", + }, +) + + +class File(proto.Message): + r"""File information about the related binary/library used by an + executable, or the script used by a script interpreter + + Attributes: + path (str): + Absolute path of the file as a JSON encoded + string. + size (int): + Size of the file in bytes. + sha256 (str): + SHA256 hash of the first hashed_size bytes of the file + encoded as a hex string. If hashed_size == size, sha256 + represents the SHA256 hash of the entire file. + hashed_size (int): + The length in bytes of the file prefix that was hashed. If + hashed_size == size, any hashes reported represent the + entire file. + partially_hashed (bool): + True when the hash covers only a prefix of + the file. + contents (str): + Prefix of the file contents as a JSON-encoded + string. + disk_path (google.cloud.securitycenter_v2.types.File.DiskPath): + Path of the file in terms of underlying + disk/partition identifiers. + """ + + class DiskPath(proto.Message): + r"""Path of the file in terms of underlying disk/partition + identifiers. + + Attributes: + partition_uuid (str): + UUID of the partition (format + https://wiki.archlinux.org/title/persistent_block_device_naming#by-uuid) + relative_path (str): + Relative path of the file in the partition as a JSON encoded + string. Example: /home/user1/executable_file.sh + """ + + partition_uuid: str = proto.Field( + proto.STRING, + number=1, + ) + relative_path: str = proto.Field( + proto.STRING, + number=2, + ) + + path: str = proto.Field( + proto.STRING, + number=1, + ) + size: int = proto.Field( + proto.INT64, + number=2, + ) + sha256: str = proto.Field( + proto.STRING, + number=3, + ) + hashed_size: int = proto.Field( + proto.INT64, + number=4, + ) + partially_hashed: bool = proto.Field( + proto.BOOL, + number=5, + ) + contents: str = proto.Field( + proto.STRING, + number=6, + ) + disk_path: DiskPath = proto.Field( + proto.MESSAGE, + number=7, + message=DiskPath, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/finding.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/finding.py new file mode 100644 index 000000000000..00d19bc2ab25 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/finding.py @@ -0,0 +1,690 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.securitycenter_v2.types import ( + compliance, + connection, + contact_details, + container, +) +from google.cloud.securitycenter_v2.types import external_system, file, iam_binding +from google.cloud.securitycenter_v2.types import attack_exposure as gcs_attack_exposure +from google.cloud.securitycenter_v2.types import ( + backup_disaster_recovery as gcs_backup_disaster_recovery, +) +from google.cloud.securitycenter_v2.types import ( + cloud_dlp_data_profile as gcs_cloud_dlp_data_profile, +) +from google.cloud.securitycenter_v2.types import ( + cloud_dlp_inspection as gcs_cloud_dlp_inspection, +) +from google.cloud.securitycenter_v2.types import exfiltration as gcs_exfiltration +from google.cloud.securitycenter_v2.types import kernel_rootkit as gcs_kernel_rootkit +from google.cloud.securitycenter_v2.types import mitre_attack as gcs_mitre_attack +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import ( + security_posture as gcs_security_posture, +) +from google.cloud.securitycenter_v2.types import vulnerability as gcs_vulnerability +from google.cloud.securitycenter_v2.types import access as gcs_access +from google.cloud.securitycenter_v2.types import application as gcs_application +from google.cloud.securitycenter_v2.types import database as gcs_database +from google.cloud.securitycenter_v2.types import indicator as gcs_indicator +from google.cloud.securitycenter_v2.types import kubernetes as gcs_kubernetes +from google.cloud.securitycenter_v2.types import load_balancer, log_entry +from google.cloud.securitycenter_v2.types import org_policy, process + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v2", + manifest={ + "Finding", + }, +) + + +class Finding(proto.Message): + r"""Security Command Center finding. + + A finding is a record of assessment data like security, risk, + health, or privacy, that is ingested into Security Command + Center for presentation, notification, analysis, policy testing, + and enforcement. For example, a cross-site scripting (XSS) + vulnerability in an App Engine application is a finding. + + Attributes: + name (str): + The `relative resource + name `__ + of the finding. The following list shows some examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + canonical_name (str): + Output only. The canonical name of the finding. The + following list shows some examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + The prefix is the closest CRM ancestor of the resource + associated with the finding. + parent (str): + The relative resource name of the source and location the + finding belongs to. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + This field is immutable after creation time. The following + list shows some examples: + + - ``organizations/{organization_id}/sources/{source_id}`` + - ``folders/{folders_id}/sources/{source_id}`` + - ``projects/{projects_id}/sources/{source_id}`` + - + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}`` + + - ``folders/{folders_id}/sources/{source_id}/locations/{location_id}`` + - ``projects/{projects_id}/sources/{source_id}/locations/{location_id}`` + resource_name (str): + Immutable. 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. + state (google.cloud.securitycenter_v2.types.Finding.State): + Output only. The state of the finding. + category (str): + Immutable. The additional taxonomy group within findings + from a given source. Example: "XSS_FLASH_INJECTION". + external_uri (str): + The URI that, if available, points to a web + page outside of Security Command Center where + additional information about the finding can be + found. This field is guaranteed to be either + empty or a well formed URL. + 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. + security_marks (google.cloud.securitycenter_v2.types.SecurityMarks): + Output only. User specified security marks. + These marks are entirely managed by the user and + come from the SecurityMarks resource that + belongs to the finding. + 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 + later resolved, then this time reflects when the + finding was resolved. This must not be set to a + value greater than the current timestamp. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the finding + was created in Security Command Center. + severity (google.cloud.securitycenter_v2.types.Finding.Severity): + The severity of the finding. This field is + managed by the source that writes the finding. + mute (google.cloud.securitycenter_v2.types.Finding.Mute): + Indicates the mute state of a finding (either + muted, unmuted or undefined). Unlike other + attributes of a finding, a finding provider + shouldn't set the value of mute. + finding_class (google.cloud.securitycenter_v2.types.Finding.FindingClass): + The class of the finding. + indicator (google.cloud.securitycenter_v2.types.Indicator): + Represents what's commonly known as an *indicator of + compromise* (IoC) in computer forensics. This is an artifact + observed on a network or in an operating system that, with + high confidence, indicates a computer intrusion. For more + information, see `Indicator of + compromise `__. + vulnerability (google.cloud.securitycenter_v2.types.Vulnerability): + Represents vulnerability-specific fields like + CVE and CVSS scores. CVE stands for Common + Vulnerabilities and Exposures + (https://cve.mitre.org/about/) + mute_update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time this + finding was muted or unmuted. + external_systems (MutableMapping[str, google.cloud.securitycenter_v2.types.ExternalSystem]): + Output only. Third party SIEM/SOAR fields + within SCC, contains external system information + and external system finding fields. + mitre_attack (google.cloud.securitycenter_v2.types.MitreAttack): + MITRE ATT&CK tactics and techniques related + to this finding. See: https://attack.mitre.org + access (google.cloud.securitycenter_v2.types.Access): + Access details associated with the finding, + such as more information on the caller, which + method was accessed, and from where. + connections (MutableSequence[google.cloud.securitycenter_v2.types.Connection]): + Contains information about the IP connection + associated with the finding. + mute_initiator (str): + Records additional information about the mute operation, for + example, the `mute + configuration `__ + that muted the finding and the user who muted the finding. + processes (MutableSequence[google.cloud.securitycenter_v2.types.Process]): + Represents operating system processes + associated with the Finding. + contacts (MutableMapping[str, google.cloud.securitycenter_v2.types.ContactDetails]): + Output only. Map containing the points of contact for the + given finding. The key represents the type of contact, while + the value contains a list of all the contacts that pertain. + Please refer to: + https://cloud.google.com/resource-manager/docs/managing-notification-contacts#notification-categories + + :: + + { + "security": { + "contacts": [ + { + "email": "person1@company.com" + }, + { + "email": "person2@company.com" + } + ] + } + } + compliances (MutableSequence[google.cloud.securitycenter_v2.types.Compliance]): + Contains compliance information for security + standards associated to the finding. + parent_display_name (str): + Output only. The human readable display name + of the finding source such as "Event Threat + Detection" or "Security Health Analytics". + description (str): + Contains more details about the finding. + exfiltration (google.cloud.securitycenter_v2.types.Exfiltration): + Represents exfiltrations associated with the + finding. + iam_bindings (MutableSequence[google.cloud.securitycenter_v2.types.IamBinding]): + Represents IAM bindings associated with the + finding. + next_steps (str): + Steps to address the finding. + module_name (str): + Unique identifier of the module which + generated the finding. Example: + + folders/598186756061/securityHealthAnalyticsSettings/customModules/56799441161885 + containers (MutableSequence[google.cloud.securitycenter_v2.types.Container]): + Containers associated with the finding. This + field provides information for both Kubernetes + and non-Kubernetes containers. + kubernetes (google.cloud.securitycenter_v2.types.Kubernetes): + Kubernetes resources associated with the + finding. + database (google.cloud.securitycenter_v2.types.Database): + Database associated with the finding. + attack_exposure (google.cloud.securitycenter_v2.types.AttackExposure): + The results of an attack path simulation + relevant to this finding. + files (MutableSequence[google.cloud.securitycenter_v2.types.File]): + File associated with the finding. + cloud_dlp_inspection (google.cloud.securitycenter_v2.types.CloudDlpInspection): + Cloud Data Loss Prevention (Cloud DLP) + inspection results that are associated with the + finding. + cloud_dlp_data_profile (google.cloud.securitycenter_v2.types.CloudDlpDataProfile): + Cloud DLP data profile that is associated + with the finding. + kernel_rootkit (google.cloud.securitycenter_v2.types.KernelRootkit): + Signature of the kernel rootkit. + org_policies (MutableSequence[google.cloud.securitycenter_v2.types.OrgPolicy]): + Contains information about the org policies + associated with the finding. + application (google.cloud.securitycenter_v2.types.Application): + Represents an application associated with the + finding. + backup_disaster_recovery (google.cloud.securitycenter_v2.types.BackupDisasterRecovery): + Fields related to Backup and DR findings. + security_posture (google.cloud.securitycenter_v2.types.SecurityPosture): + The security posture associated with the + finding. + log_entries (MutableSequence[google.cloud.securitycenter_v2.types.LogEntry]): + Log entries that are relevant to the finding. + load_balancers (MutableSequence[google.cloud.securitycenter_v2.types.LoadBalancer]): + The load balancers associated with the + finding. + """ + + class State(proto.Enum): + r"""The state of the finding. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + 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 + longer active. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + class Severity(proto.Enum): + r"""The severity of the finding. + + Values: + SEVERITY_UNSPECIFIED (0): + This value is used for findings when a source + doesn't write a severity value. + CRITICAL (1): + Vulnerability: + + 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. + + 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. + 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. + 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. + """ + SEVERITY_UNSPECIFIED = 0 + CRITICAL = 1 + HIGH = 2 + MEDIUM = 3 + LOW = 4 + + class Mute(proto.Enum): + r"""Mute state a finding can be in. + + Values: + MUTE_UNSPECIFIED (0): + Unspecified. + MUTED (1): + Finding has been muted. + UNMUTED (2): + Finding has been unmuted. + UNDEFINED (3): + Finding has never been muted/unmuted. + """ + MUTE_UNSPECIFIED = 0 + MUTED = 1 + UNMUTED = 2 + UNDEFINED = 3 + + class FindingClass(proto.Enum): + r"""Represents what kind of Finding it is. + + Values: + FINDING_CLASS_UNSPECIFIED (0): + Unspecified finding class. + THREAT (1): + Describes unwanted or malicious activity. + VULNERABILITY (2): + Describes a potential weakness in software + that increases risk to Confidentiality & + Integrity & Availability. + MISCONFIGURATION (3): + Describes a potential weakness in cloud + resource/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. + POSTURE_VIOLATION (6): + Describes a potential security risk due to a + change in the security posture. + """ + FINDING_CLASS_UNSPECIFIED = 0 + THREAT = 1 + VULNERABILITY = 2 + MISCONFIGURATION = 3 + OBSERVATION = 4 + SCC_ERROR = 5 + POSTURE_VIOLATION = 6 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=2, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + resource_name: str = proto.Field( + proto.STRING, + number=4, + ) + state: State = proto.Field( + proto.ENUM, + number=6, + enum=State, + ) + category: str = proto.Field( + proto.STRING, + number=7, + ) + external_uri: str = proto.Field( + proto.STRING, + number=8, + ) + source_properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=9, + message=struct_pb2.Value, + ) + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=10, + message=gcs_security_marks.SecurityMarks, + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + severity: Severity = proto.Field( + proto.ENUM, + number=14, + enum=Severity, + ) + mute: Mute = proto.Field( + proto.ENUM, + number=15, + enum=Mute, + ) + finding_class: FindingClass = proto.Field( + proto.ENUM, + number=16, + enum=FindingClass, + ) + indicator: gcs_indicator.Indicator = proto.Field( + proto.MESSAGE, + number=17, + message=gcs_indicator.Indicator, + ) + vulnerability: gcs_vulnerability.Vulnerability = proto.Field( + proto.MESSAGE, + number=18, + message=gcs_vulnerability.Vulnerability, + ) + mute_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=19, + message=timestamp_pb2.Timestamp, + ) + external_systems: MutableMapping[ + str, external_system.ExternalSystem + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=20, + message=external_system.ExternalSystem, + ) + mitre_attack: gcs_mitre_attack.MitreAttack = proto.Field( + proto.MESSAGE, + number=21, + message=gcs_mitre_attack.MitreAttack, + ) + access: gcs_access.Access = proto.Field( + proto.MESSAGE, + number=22, + message=gcs_access.Access, + ) + connections: MutableSequence[connection.Connection] = proto.RepeatedField( + proto.MESSAGE, + number=23, + message=connection.Connection, + ) + mute_initiator: str = proto.Field( + proto.STRING, + number=24, + ) + processes: MutableSequence[process.Process] = proto.RepeatedField( + proto.MESSAGE, + number=25, + message=process.Process, + ) + contacts: MutableMapping[str, contact_details.ContactDetails] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=26, + message=contact_details.ContactDetails, + ) + compliances: MutableSequence[compliance.Compliance] = proto.RepeatedField( + proto.MESSAGE, + number=27, + message=compliance.Compliance, + ) + parent_display_name: str = proto.Field( + proto.STRING, + number=29, + ) + description: str = proto.Field( + proto.STRING, + number=30, + ) + exfiltration: gcs_exfiltration.Exfiltration = proto.Field( + proto.MESSAGE, + number=31, + message=gcs_exfiltration.Exfiltration, + ) + iam_bindings: MutableSequence[iam_binding.IamBinding] = proto.RepeatedField( + proto.MESSAGE, + number=32, + message=iam_binding.IamBinding, + ) + next_steps: str = proto.Field( + proto.STRING, + number=33, + ) + module_name: str = proto.Field( + proto.STRING, + number=34, + ) + containers: MutableSequence[container.Container] = proto.RepeatedField( + proto.MESSAGE, + number=35, + message=container.Container, + ) + kubernetes: gcs_kubernetes.Kubernetes = proto.Field( + proto.MESSAGE, + number=36, + message=gcs_kubernetes.Kubernetes, + ) + database: gcs_database.Database = proto.Field( + proto.MESSAGE, + number=37, + message=gcs_database.Database, + ) + attack_exposure: gcs_attack_exposure.AttackExposure = proto.Field( + proto.MESSAGE, + number=38, + message=gcs_attack_exposure.AttackExposure, + ) + files: MutableSequence[file.File] = proto.RepeatedField( + proto.MESSAGE, + number=39, + message=file.File, + ) + cloud_dlp_inspection: gcs_cloud_dlp_inspection.CloudDlpInspection = proto.Field( + proto.MESSAGE, + number=40, + message=gcs_cloud_dlp_inspection.CloudDlpInspection, + ) + cloud_dlp_data_profile: gcs_cloud_dlp_data_profile.CloudDlpDataProfile = ( + proto.Field( + proto.MESSAGE, + number=41, + message=gcs_cloud_dlp_data_profile.CloudDlpDataProfile, + ) + ) + kernel_rootkit: gcs_kernel_rootkit.KernelRootkit = proto.Field( + proto.MESSAGE, + number=42, + message=gcs_kernel_rootkit.KernelRootkit, + ) + org_policies: MutableSequence[org_policy.OrgPolicy] = proto.RepeatedField( + proto.MESSAGE, + number=43, + message=org_policy.OrgPolicy, + ) + application: gcs_application.Application = proto.Field( + proto.MESSAGE, + number=45, + message=gcs_application.Application, + ) + backup_disaster_recovery: gcs_backup_disaster_recovery.BackupDisasterRecovery = ( + proto.Field( + proto.MESSAGE, + number=47, + message=gcs_backup_disaster_recovery.BackupDisasterRecovery, + ) + ) + security_posture: gcs_security_posture.SecurityPosture = proto.Field( + proto.MESSAGE, + number=48, + message=gcs_security_posture.SecurityPosture, + ) + log_entries: MutableSequence[log_entry.LogEntry] = proto.RepeatedField( + proto.MESSAGE, + number=49, + message=log_entry.LogEntry, + ) + load_balancers: MutableSequence[load_balancer.LoadBalancer] = proto.RepeatedField( + proto.MESSAGE, + number=50, + message=load_balancer.LoadBalancer, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/iam_binding.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/iam_binding.py new file mode 100644 index 000000000000..ce9eaaef14b6 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/iam_binding.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "IamBinding", + }, +) + + +class IamBinding(proto.Message): + r"""Represents a particular IAM binding, which captures a + member's role addition, removal, or state. + + Attributes: + action (google.cloud.securitycenter_v2.types.IamBinding.Action): + The action that was performed on a Binding. + role (str): + Role that is assigned to "members". + For example, "roles/viewer", "roles/editor", or + "roles/owner". + member (str): + A single identity requesting access for a + Cloud Platform resource, for example, + "foo@google.com". + """ + + class Action(proto.Enum): + r"""The type of action performed on a Binding in a policy. + + Values: + ACTION_UNSPECIFIED (0): + Unspecified. + ADD (1): + Addition of a Binding. + REMOVE (2): + Removal of a Binding. + """ + ACTION_UNSPECIFIED = 0 + ADD = 1 + REMOVE = 2 + + action: Action = proto.Field( + proto.ENUM, + number=1, + enum=Action, + ) + role: str = proto.Field( + proto.STRING, + number=2, + ) + member: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/indicator.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/indicator.py new file mode 100644 index 000000000000..1076b985c5e5 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/indicator.py @@ -0,0 +1,192 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "Indicator", + }, +) + + +class Indicator(proto.Message): + r"""Represents what's commonly known as an *indicator of compromise* + (IoC) in computer forensics. This is an artifact observed on a + network or in an operating system that, with high confidence, + indicates a computer intrusion. For more information, see `Indicator + of + compromise `__. + + Attributes: + ip_addresses (MutableSequence[str]): + The list of IP addresses that are associated + with the finding. + domains (MutableSequence[str]): + List of domains associated to the Finding. + signatures (MutableSequence[google.cloud.securitycenter_v2.types.Indicator.ProcessSignature]): + The list of matched signatures indicating + that the given process is present in the + environment. + uris (MutableSequence[str]): + The list of URIs associated to the Findings. + """ + + class ProcessSignature(proto.Message): + r"""Indicates what signature matched this process. + + 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: + memory_hash_signature (google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.MemoryHashSignature): + Signature indicating that a binary family was + matched. + + This field is a member of `oneof`_ ``signature``. + yara_rule_signature (google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.YaraRuleSignature): + Signature indicating that a YARA rule was + matched. + + This field is a member of `oneof`_ ``signature``. + signature_type (google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.SignatureType): + Describes the type of resource associated + with the signature. + """ + + class SignatureType(proto.Enum): + r"""Possible resource types to be associated with a signature. + + Values: + SIGNATURE_TYPE_UNSPECIFIED (0): + The default signature type. + SIGNATURE_TYPE_PROCESS (1): + Used for signatures concerning processes. + SIGNATURE_TYPE_FILE (2): + Used for signatures concerning disks. + """ + SIGNATURE_TYPE_UNSPECIFIED = 0 + SIGNATURE_TYPE_PROCESS = 1 + SIGNATURE_TYPE_FILE = 2 + + class MemoryHashSignature(proto.Message): + r"""A signature corresponding to memory page hashes. + + Attributes: + binary_family (str): + The binary family. + detections (MutableSequence[google.cloud.securitycenter_v2.types.Indicator.ProcessSignature.MemoryHashSignature.Detection]): + The list of memory hash detections + contributing to the binary family match. + """ + + class Detection(proto.Message): + r"""Memory hash detection contributing to the binary family + match. + + Attributes: + binary (str): + The name of the binary associated with the + memory hash signature detection. + percent_pages_matched (float): + The percentage of memory page hashes in the + signature that were matched. + """ + + binary: str = proto.Field( + proto.STRING, + number=2, + ) + percent_pages_matched: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + binary_family: str = proto.Field( + proto.STRING, + number=1, + ) + detections: MutableSequence[ + "Indicator.ProcessSignature.MemoryHashSignature.Detection" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="Indicator.ProcessSignature.MemoryHashSignature.Detection", + ) + + class YaraRuleSignature(proto.Message): + r"""A signature corresponding to a YARA rule. + + Attributes: + yara_rule (str): + The name of the YARA rule. + """ + + yara_rule: str = proto.Field( + proto.STRING, + number=5, + ) + + memory_hash_signature: "Indicator.ProcessSignature.MemoryHashSignature" = ( + proto.Field( + proto.MESSAGE, + number=6, + oneof="signature", + message="Indicator.ProcessSignature.MemoryHashSignature", + ) + ) + yara_rule_signature: "Indicator.ProcessSignature.YaraRuleSignature" = ( + proto.Field( + proto.MESSAGE, + number=7, + oneof="signature", + message="Indicator.ProcessSignature.YaraRuleSignature", + ) + ) + signature_type: "Indicator.ProcessSignature.SignatureType" = proto.Field( + proto.ENUM, + number=8, + enum="Indicator.ProcessSignature.SignatureType", + ) + + ip_addresses: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + domains: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + signatures: MutableSequence[ProcessSignature] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=ProcessSignature, + ) + uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/kernel_rootkit.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/kernel_rootkit.py new file mode 100644 index 000000000000..edc5dd14fb7a --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/kernel_rootkit.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "KernelRootkit", + }, +) + + +class KernelRootkit(proto.Message): + r"""Kernel mode rootkit signatures. + + Attributes: + name (str): + Rootkit name, when available. + unexpected_code_modification (bool): + True if unexpected modifications of kernel + code memory are present. + unexpected_read_only_data_modification (bool): + True if unexpected modifications of kernel + read-only data memory are present. + unexpected_ftrace_handler (bool): + True if ``ftrace`` points are present with callbacks + pointing to regions that are not in the expected kernel or + module code range. + unexpected_kprobe_handler (bool): + True if ``kprobe`` points are present with callbacks + pointing to regions that are not in the expected kernel or + module code range. + unexpected_kernel_code_pages (bool): + True if kernel code pages that are not in the + expected kernel or module code regions are + present. + unexpected_system_call_handler (bool): + True if system call handlers that are are not + in the expected kernel or module code regions + are present. + unexpected_interrupt_handler (bool): + True if interrupt handlers that are are not + in the expected kernel or module code regions + are present. + unexpected_processes_in_runqueue (bool): + True if unexpected processes in the scheduler + run queue are present. Such processes are in the + run queue, but not in the process task list. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + unexpected_code_modification: bool = proto.Field( + proto.BOOL, + number=2, + ) + unexpected_read_only_data_modification: bool = proto.Field( + proto.BOOL, + number=3, + ) + unexpected_ftrace_handler: bool = proto.Field( + proto.BOOL, + number=4, + ) + unexpected_kprobe_handler: bool = proto.Field( + proto.BOOL, + number=5, + ) + unexpected_kernel_code_pages: bool = proto.Field( + proto.BOOL, + number=6, + ) + unexpected_system_call_handler: bool = proto.Field( + proto.BOOL, + number=7, + ) + unexpected_interrupt_handler: bool = proto.Field( + proto.BOOL, + number=8, + ) + unexpected_processes_in_runqueue: bool = proto.Field( + proto.BOOL, + number=9, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/kubernetes.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/kubernetes.py new file mode 100644 index 000000000000..1f47a938f512 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/kubernetes.py @@ -0,0 +1,398 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 + +from google.cloud.securitycenter_v2.types import container, label + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v2", + manifest={ + "Kubernetes", + }, +) + + +class Kubernetes(proto.Message): + r"""Kubernetes-related attributes. + + Attributes: + pods (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Pod]): + Kubernetes + `Pods `__ + associated with the finding. This field contains Pod records + for each container that is owned by a Pod. + nodes (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Node]): + Provides Kubernetes + `node `__ + information. + node_pools (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.NodePool]): + GKE `node + pools `__ + associated with the finding. This field contains node pool + information for each node, when it is available. + roles (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Role]): + Provides Kubernetes role information for findings that + involve `Roles or + ClusterRoles `__. + bindings (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Binding]): + Provides Kubernetes role binding information for findings + that involve `RoleBindings or + ClusterRoleBindings `__. + access_reviews (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.AccessReview]): + Provides information on any Kubernetes access + reviews (privilege checks) relevant to the + finding. + objects (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Object]): + Kubernetes objects related to the finding. + """ + + class Pod(proto.Message): + r"""A Kubernetes Pod. + + Attributes: + ns (str): + Kubernetes Pod namespace. + name (str): + Kubernetes Pod name. + labels (MutableSequence[google.cloud.securitycenter_v2.types.Label]): + Pod labels. For Kubernetes containers, these + are applied to the container. + containers (MutableSequence[google.cloud.securitycenter_v2.types.Container]): + Pod containers associated with this finding, + if any. + """ + + ns: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + labels: MutableSequence[label.Label] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=label.Label, + ) + containers: MutableSequence[container.Container] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=container.Container, + ) + + class Node(proto.Message): + r"""Kubernetes nodes associated with the finding. + + Attributes: + name (str): + `Full resource + name `__ of + the Compute Engine VM running the cluster node. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + class NodePool(proto.Message): + r"""Provides GKE node pool information. + + Attributes: + name (str): + Kubernetes node pool name. + nodes (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Node]): + Nodes associated with the finding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + nodes: MutableSequence["Kubernetes.Node"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Kubernetes.Node", + ) + + class Role(proto.Message): + r"""Kubernetes Role or ClusterRole. + + Attributes: + kind (google.cloud.securitycenter_v2.types.Kubernetes.Role.Kind): + Role type. + ns (str): + Role namespace. + name (str): + Role name. + """ + + class Kind(proto.Enum): + r"""Types of Kubernetes roles. + + Values: + KIND_UNSPECIFIED (0): + Role type is not specified. + ROLE (1): + Kubernetes Role. + CLUSTER_ROLE (2): + Kubernetes ClusterRole. + """ + KIND_UNSPECIFIED = 0 + ROLE = 1 + CLUSTER_ROLE = 2 + + kind: "Kubernetes.Role.Kind" = proto.Field( + proto.ENUM, + number=1, + enum="Kubernetes.Role.Kind", + ) + ns: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + class Binding(proto.Message): + r"""Represents a Kubernetes RoleBinding or ClusterRoleBinding. + + Attributes: + ns (str): + Namespace for the binding. + name (str): + Name for the binding. + role (google.cloud.securitycenter_v2.types.Kubernetes.Role): + The Role or ClusterRole referenced by the + binding. + subjects (MutableSequence[google.cloud.securitycenter_v2.types.Kubernetes.Subject]): + Represents one or more subjects that are + bound to the role. Not always available for + PATCH requests. + """ + + ns: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + role: "Kubernetes.Role" = proto.Field( + proto.MESSAGE, + number=3, + message="Kubernetes.Role", + ) + subjects: MutableSequence["Kubernetes.Subject"] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="Kubernetes.Subject", + ) + + class Subject(proto.Message): + r"""Represents a Kubernetes subject. + + Attributes: + kind (google.cloud.securitycenter_v2.types.Kubernetes.Subject.AuthType): + Authentication type for the subject. + ns (str): + Namespace for the subject. + name (str): + Name for the subject. + """ + + class AuthType(proto.Enum): + r"""Auth types that can be used for the subject's kind field. + + Values: + AUTH_TYPE_UNSPECIFIED (0): + Authentication is not specified. + USER (1): + User with valid certificate. + SERVICEACCOUNT (2): + Users managed by Kubernetes API with + credentials stored as secrets. + GROUP (3): + Collection of users. + """ + AUTH_TYPE_UNSPECIFIED = 0 + USER = 1 + SERVICEACCOUNT = 2 + GROUP = 3 + + kind: "Kubernetes.Subject.AuthType" = proto.Field( + proto.ENUM, + number=1, + enum="Kubernetes.Subject.AuthType", + ) + ns: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + + class AccessReview(proto.Message): + r"""Conveys information about a Kubernetes access review (such as one + returned by a + ```kubectl auth can-i`` `__ + command) that was involved in a finding. + + Attributes: + group (str): + The API group of the resource. "*" means all. + ns (str): + Namespace of the action being requested. + Currently, there is no distinction between no + namespace and all namespaces. Both are + represented by "" (empty). + name (str): + The name of the resource being requested. + Empty means all. + resource (str): + The optional resource type requested. "*" means all. + subresource (str): + The optional subresource type. + verb (str): + A Kubernetes resource API verb, like get, list, watch, + create, update, delete, proxy. "*" means all. + version (str): + The API version of the resource. "*" means all. + """ + + group: str = proto.Field( + proto.STRING, + number=1, + ) + ns: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( + proto.STRING, + number=3, + ) + resource: str = proto.Field( + proto.STRING, + number=4, + ) + subresource: str = proto.Field( + proto.STRING, + number=5, + ) + verb: str = proto.Field( + proto.STRING, + number=6, + ) + version: str = proto.Field( + proto.STRING, + number=7, + ) + + class Object(proto.Message): + r"""Kubernetes object related to the finding, uniquely identified + by GKNN. Used if the object Kind is not one of Pod, Node, + NodePool, Binding, or AccessReview. + + Attributes: + group (str): + Kubernetes object group, such as + "policy.k8s.io/v1". + kind (str): + Kubernetes object kind, such as "Namespace". + ns (str): + Kubernetes object namespace. Must be a valid + DNS label. Named "ns" to avoid collision with + C++ namespace keyword. For details see + https://kubernetes.io/docs/tasks/administer-cluster/namespaces/. + name (str): + Kubernetes object name. For details see + https://kubernetes.io/docs/concepts/overview/working-with-objects/names/. + containers (MutableSequence[google.cloud.securitycenter_v2.types.Container]): + Pod containers associated with this finding, + if any. + """ + + group: str = proto.Field( + proto.STRING, + number=1, + ) + kind: str = proto.Field( + proto.STRING, + number=2, + ) + ns: str = proto.Field( + proto.STRING, + number=3, + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + containers: MutableSequence[container.Container] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=container.Container, + ) + + pods: MutableSequence[Pod] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Pod, + ) + nodes: MutableSequence[Node] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Node, + ) + node_pools: MutableSequence[NodePool] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=NodePool, + ) + roles: MutableSequence[Role] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Role, + ) + bindings: MutableSequence[Binding] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Binding, + ) + access_reviews: MutableSequence[AccessReview] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=AccessReview, + ) + objects: MutableSequence[Object] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Object, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/label.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/label.py new file mode 100644 index 000000000000..5ccb9072d756 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/label.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "Label", + }, +) + + +class Label(proto.Message): + r"""Represents a generic name-value label. A label has separate name and + value fields to support filtering with the ``contains()`` function. + For more information, see `Filtering on array-type + fields `__. + + Attributes: + name (str): + Name of the label. + value (str): + Value that corresponds to the label's name. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/load_balancer.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/load_balancer.py new file mode 100644 index 000000000000..687c8a09fdc2 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/load_balancer.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "LoadBalancer", + }, +) + + +class LoadBalancer(proto.Message): + r"""Contains information related to the load balancer associated + with the finding. + + Attributes: + name (str): + The name of the load balancer associated with + the finding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/log_entry.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/log_entry.py new file mode 100644 index 000000000000..df29ce9bfbe4 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/log_entry.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "LogEntry", + "CloudLoggingEntry", + }, +) + + +class LogEntry(proto.Message): + r"""An individual entry in a log. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_logging_entry (google.cloud.securitycenter_v2.types.CloudLoggingEntry): + An individual entry in a log stored in Cloud + Logging. + + This field is a member of `oneof`_ ``log_entry``. + """ + + cloud_logging_entry: "CloudLoggingEntry" = proto.Field( + proto.MESSAGE, + number=1, + oneof="log_entry", + message="CloudLoggingEntry", + ) + + +class CloudLoggingEntry(proto.Message): + r"""Metadata taken from a `Cloud Logging + LogEntry `__ + + Attributes: + insert_id (str): + A unique identifier for the log entry. + log_id (str): + The type of the log (part of ``log_name``. ``log_name`` is + the resource name of the log to which this log entry + belongs). For example: + ``cloudresourcemanager.googleapis.com/activity`` Note that + this field is not URL-encoded, unlike in ``LogEntry``. + resource_container (str): + The organization, folder, or project of the + monitored resource that produced this log entry. + timestamp (google.protobuf.timestamp_pb2.Timestamp): + The time the event described by the log entry + occurred. + """ + + insert_id: str = proto.Field( + proto.STRING, + number=1, + ) + log_id: str = proto.Field( + proto.STRING, + number=2, + ) + resource_container: str = proto.Field( + proto.STRING, + number=3, + ) + timestamp: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/mitre_attack.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/mitre_attack.py new file mode 100644 index 000000000000..ef706800ae64 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/mitre_attack.py @@ -0,0 +1,322 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "MitreAttack", + }, +) + + +class MitreAttack(proto.Message): + r"""MITRE ATT&CK tactics and techniques related to this finding. + See: https://attack.mitre.org + + Attributes: + primary_tactic (google.cloud.securitycenter_v2.types.MitreAttack.Tactic): + The MITRE ATT&CK tactic most closely + represented by this finding, if any. + primary_techniques (MutableSequence[google.cloud.securitycenter_v2.types.MitreAttack.Technique]): + The MITRE ATT&CK technique most closely represented by this + finding, if any. primary_techniques is a repeated field + because there are multiple levels of MITRE ATT&CK + techniques. If the technique most closely represented by + this finding is a sub-technique (e.g. + ``SCANNING_IP_BLOCKS``), both the sub-technique and its + parent technique(s) will be listed (e.g. + ``SCANNING_IP_BLOCKS``, ``ACTIVE_SCANNING``). + additional_tactics (MutableSequence[google.cloud.securitycenter_v2.types.MitreAttack.Tactic]): + Additional MITRE ATT&CK tactics related to + this finding, if any. + additional_techniques (MutableSequence[google.cloud.securitycenter_v2.types.MitreAttack.Technique]): + Additional MITRE ATT&CK techniques related to + this finding, if any, along with any of their + respective parent techniques. + version (str): + The MITRE ATT&CK version referenced by the + above fields. E.g. "8". + """ + + class Tactic(proto.Enum): + r"""MITRE ATT&CK tactics that can be referenced by SCC findings. + See: https://attack.mitre.org/tactics/enterprise/ + + Values: + TACTIC_UNSPECIFIED (0): + Unspecified value. + RECONNAISSANCE (1): + TA0043 + RESOURCE_DEVELOPMENT (2): + TA0042 + INITIAL_ACCESS (5): + TA0001 + EXECUTION (3): + TA0002 + PERSISTENCE (6): + TA0003 + PRIVILEGE_ESCALATION (8): + TA0004 + DEFENSE_EVASION (7): + TA0005 + CREDENTIAL_ACCESS (9): + TA0006 + DISCOVERY (10): + TA0007 + LATERAL_MOVEMENT (11): + TA0008 + COLLECTION (12): + TA0009 + COMMAND_AND_CONTROL (4): + TA0011 + EXFILTRATION (13): + TA0010 + IMPACT (14): + TA0040 + """ + TACTIC_UNSPECIFIED = 0 + RECONNAISSANCE = 1 + RESOURCE_DEVELOPMENT = 2 + INITIAL_ACCESS = 5 + EXECUTION = 3 + PERSISTENCE = 6 + PRIVILEGE_ESCALATION = 8 + DEFENSE_EVASION = 7 + CREDENTIAL_ACCESS = 9 + DISCOVERY = 10 + LATERAL_MOVEMENT = 11 + COLLECTION = 12 + COMMAND_AND_CONTROL = 4 + EXFILTRATION = 13 + IMPACT = 14 + + class Technique(proto.Enum): + r"""MITRE ATT&CK techniques that can be referenced by SCC + findings. See: https://attack.mitre.org/techniques/enterprise/ + Next ID: 59 + + Values: + TECHNIQUE_UNSPECIFIED (0): + Unspecified value. + MASQUERADING (49): + T1036 + MATCH_LEGITIMATE_NAME_OR_LOCATION (50): + T1036.005 + BOOT_OR_LOGON_INITIALIZATION_SCRIPTS (37): + T1037 + STARTUP_ITEMS (38): + T1037.005 + NETWORK_SERVICE_DISCOVERY (32): + T1046 + PROCESS_DISCOVERY (56): + T1057 + COMMAND_AND_SCRIPTING_INTERPRETER (6): + T1059 + UNIX_SHELL (7): + T1059.004 + PERMISSION_GROUPS_DISCOVERY (18): + T1069 + CLOUD_GROUPS (19): + T1069.003 + APPLICATION_LAYER_PROTOCOL (45): + T1071 + DNS (46): + T1071.004 + SOFTWARE_DEPLOYMENT_TOOLS (47): + T1072 + VALID_ACCOUNTS (14): + T1078 + DEFAULT_ACCOUNTS (35): + T1078.001 + LOCAL_ACCOUNTS (15): + T1078.003 + CLOUD_ACCOUNTS (16): + T1078.004 + PROXY (9): + T1090 + EXTERNAL_PROXY (10): + T1090.002 + MULTI_HOP_PROXY (11): + T1090.003 + ACCOUNT_MANIPULATION (22): + T1098 + ADDITIONAL_CLOUD_CREDENTIALS (40): + T1098.001 + SSH_AUTHORIZED_KEYS (23): + T1098.004 + ADDITIONAL_CONTAINER_CLUSTER_ROLES (58): + T1098.006 + INGRESS_TOOL_TRANSFER (3): + T1105 + NATIVE_API (4): + T1106 + BRUTE_FORCE (44): + T1110 + SHARED_MODULES (5): + T1129 + ACCESS_TOKEN_MANIPULATION (33): + T1134 + TOKEN_IMPERSONATION_OR_THEFT (39): + T1134.001 + EXPLOIT_PUBLIC_FACING_APPLICATION (27): + T1190 + DOMAIN_POLICY_MODIFICATION (30): + T1484 + DATA_DESTRUCTION (29): + T1485 + SERVICE_STOP (52): + T1489 + INHIBIT_SYSTEM_RECOVERY (36): + T1490 + RESOURCE_HIJACKING (8): + T1496 + NETWORK_DENIAL_OF_SERVICE (17): + T1498 + CLOUD_SERVICE_DISCOVERY (48): + T1526 + STEAL_APPLICATION_ACCESS_TOKEN (42): + T1528 + ACCOUNT_ACCESS_REMOVAL (51): + T1531 + STEAL_WEB_SESSION_COOKIE (25): + T1539 + CREATE_OR_MODIFY_SYSTEM_PROCESS (24): + T1543 + ABUSE_ELEVATION_CONTROL_MECHANISM (34): + T1548 + UNSECURED_CREDENTIALS (13): + T1552 + MODIFY_AUTHENTICATION_PROCESS (28): + T1556 + IMPAIR_DEFENSES (31): + T1562 + DISABLE_OR_MODIFY_TOOLS (55): + T1562.001 + EXFILTRATION_OVER_WEB_SERVICE (20): + T1567 + EXFILTRATION_TO_CLOUD_STORAGE (21): + T1567.002 + DYNAMIC_RESOLUTION (12): + T1568 + LATERAL_TOOL_TRANSFER (41): + T1570 + MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE (26): + T1578 + CREATE_SNAPSHOT (54): + T1578.001 + CLOUD_INFRASTRUCTURE_DISCOVERY (53): + T1580 + OBTAIN_CAPABILITIES (43): + T1588 + ACTIVE_SCANNING (1): + T1595 + SCANNING_IP_BLOCKS (2): + T1595.001 + CONTAINER_AND_RESOURCE_DISCOVERY (57): + T1613 + """ + TECHNIQUE_UNSPECIFIED = 0 + MASQUERADING = 49 + MATCH_LEGITIMATE_NAME_OR_LOCATION = 50 + BOOT_OR_LOGON_INITIALIZATION_SCRIPTS = 37 + STARTUP_ITEMS = 38 + NETWORK_SERVICE_DISCOVERY = 32 + PROCESS_DISCOVERY = 56 + COMMAND_AND_SCRIPTING_INTERPRETER = 6 + UNIX_SHELL = 7 + PERMISSION_GROUPS_DISCOVERY = 18 + CLOUD_GROUPS = 19 + APPLICATION_LAYER_PROTOCOL = 45 + DNS = 46 + SOFTWARE_DEPLOYMENT_TOOLS = 47 + VALID_ACCOUNTS = 14 + DEFAULT_ACCOUNTS = 35 + LOCAL_ACCOUNTS = 15 + CLOUD_ACCOUNTS = 16 + PROXY = 9 + EXTERNAL_PROXY = 10 + MULTI_HOP_PROXY = 11 + ACCOUNT_MANIPULATION = 22 + ADDITIONAL_CLOUD_CREDENTIALS = 40 + SSH_AUTHORIZED_KEYS = 23 + ADDITIONAL_CONTAINER_CLUSTER_ROLES = 58 + INGRESS_TOOL_TRANSFER = 3 + NATIVE_API = 4 + BRUTE_FORCE = 44 + SHARED_MODULES = 5 + ACCESS_TOKEN_MANIPULATION = 33 + TOKEN_IMPERSONATION_OR_THEFT = 39 + EXPLOIT_PUBLIC_FACING_APPLICATION = 27 + DOMAIN_POLICY_MODIFICATION = 30 + DATA_DESTRUCTION = 29 + SERVICE_STOP = 52 + INHIBIT_SYSTEM_RECOVERY = 36 + RESOURCE_HIJACKING = 8 + NETWORK_DENIAL_OF_SERVICE = 17 + CLOUD_SERVICE_DISCOVERY = 48 + STEAL_APPLICATION_ACCESS_TOKEN = 42 + ACCOUNT_ACCESS_REMOVAL = 51 + STEAL_WEB_SESSION_COOKIE = 25 + CREATE_OR_MODIFY_SYSTEM_PROCESS = 24 + ABUSE_ELEVATION_CONTROL_MECHANISM = 34 + UNSECURED_CREDENTIALS = 13 + MODIFY_AUTHENTICATION_PROCESS = 28 + IMPAIR_DEFENSES = 31 + DISABLE_OR_MODIFY_TOOLS = 55 + EXFILTRATION_OVER_WEB_SERVICE = 20 + EXFILTRATION_TO_CLOUD_STORAGE = 21 + DYNAMIC_RESOLUTION = 12 + LATERAL_TOOL_TRANSFER = 41 + MODIFY_CLOUD_COMPUTE_INFRASTRUCTURE = 26 + CREATE_SNAPSHOT = 54 + CLOUD_INFRASTRUCTURE_DISCOVERY = 53 + OBTAIN_CAPABILITIES = 43 + ACTIVE_SCANNING = 1 + SCANNING_IP_BLOCKS = 2 + CONTAINER_AND_RESOURCE_DISCOVERY = 57 + + primary_tactic: Tactic = proto.Field( + proto.ENUM, + number=1, + enum=Tactic, + ) + primary_techniques: MutableSequence[Technique] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=Technique, + ) + additional_tactics: MutableSequence[Tactic] = proto.RepeatedField( + proto.ENUM, + number=3, + enum=Tactic, + ) + additional_techniques: MutableSequence[Technique] = proto.RepeatedField( + proto.ENUM, + number=4, + enum=Technique, + ) + version: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/mute_config.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/mute_config.py new file mode 100644 index 000000000000..28df51d1d357 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/mute_config.py @@ -0,0 +1,143 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "MuteConfig", + }, +) + + +class MuteConfig(proto.Message): + r"""A mute config is a Cloud SCC resource that contains the + configuration to mute create/update events of findings. + + Attributes: + name (str): + This field will be ignored if provided on config creation. + The following list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{mute_config}`` + - + + ``organizations/{organization}locations/{location}//muteConfigs/{mute_config}`` + + - ``folders/{folder}/muteConfigs/{mute_config}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{mute_config}`` + - ``projects/{project}/muteConfigs/{mute_config}`` + - ``projects/{project}/locations/{location}/muteConfigs/{mute_config}`` + description (str): + A description of the mute config. + filter (str): + Required. An expression that defines the filter to apply + across create/update events of findings. While creating a + filter string, be mindful of the scope in which the mute + configuration is being created. E.g., If a filter contains + project = X but is created under the project = Y scope, it + might not match any findings. + + The following field and operator combinations are supported: + + - severity: ``=``, ``:`` + - category: ``=``, ``:`` + - resource.name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.folders.resource_folder: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + - finding_class: ``=``, ``:`` + - indicator.ip_addresses: ``=``, ``:`` + - indicator.domains: ``=``, ``:`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the mute + config was created. This field is set by the + server and will be ignored if provided on config + creation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time at which + the mute config was updated. This field is set + by the server and will be ignored if provided on + config creation or update. + most_recent_editor (str): + Output only. Email address of the user who + last edited the mute config. This field is set + by the server and will be ignored if provided on + config creation or update. + type_ (google.cloud.securitycenter_v2.types.MuteConfig.MuteConfigType): + Required. The type of the mute config, which + determines what type of mute state the config + affects. Immutable after creation. + """ + + class MuteConfigType(proto.Enum): + r"""The type of MuteConfig. + + Values: + MUTE_CONFIG_TYPE_UNSPECIFIED (0): + Unused. + STATIC (1): + A static mute config, which sets the static + mute state of future matching findings to muted. + Once the static mute state has been set, finding + or config modifications will not affect the + state. + """ + MUTE_CONFIG_TYPE_UNSPECIFIED = 0 + STATIC = 1 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + filter: 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, + ) + most_recent_editor: str = proto.Field( + proto.STRING, + number=6, + ) + type_: MuteConfigType = proto.Field( + proto.ENUM, + number=8, + enum=MuteConfigType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/notification_config.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/notification_config.py new file mode 100644 index 000000000000..e00250d588df --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/notification_config.py @@ -0,0 +1,127 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "NotificationConfig", + }, +) + + +class NotificationConfig(proto.Message): + r"""Cloud Security Command Center (Cloud SCC) notification + configs. + A notification config is a Cloud SCC resource that contains the + configuration to send notifications for create/update events of + findings, assets and etc. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The relative resource name of this notification config. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + The following list shows some examples: + + ``organizations/{organization_id}/locations/{location_id}/notificationConfigs/notify_public_bucket`` + + + ``folders/{folder_id}/locations/{location_id}/notificationConfigs/notify_public_bucket`` + + + ``projects/{project_id}/locations/{location_id}/notificationConfigs/notify_public_bucket`` + description (str): + The description of the notification config + (max of 1024 characters). + pubsub_topic (str): + The Pub/Sub topic to send notifications to. Its format is + "projects/[project_id]/topics/[topic]". + service_account (str): + Output only. The service account that needs + "pubsub.topics.publish" permission to publish to + the Pub/Sub topic. + streaming_config (google.cloud.securitycenter_v2.types.NotificationConfig.StreamingConfig): + The config for triggering streaming-based + notifications. + + This field is a member of `oneof`_ ``notify_config``. + """ + + class StreamingConfig(proto.Message): + r"""The config for streaming-based notifications, which send each + event as soon as it is detected. + + Attributes: + filter (str): + Expression that defines the filter to apply across + create/update events of assets or findings as specified by + the event type. The expression is a list of zero or more + restrictions combined via logical operators ``AND`` and + ``OR``. Parentheses are supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + """ + + filter: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + pubsub_topic: str = proto.Field( + proto.STRING, + number=3, + ) + service_account: str = proto.Field( + proto.STRING, + number=4, + ) + streaming_config: StreamingConfig = proto.Field( + proto.MESSAGE, + number=5, + oneof="notify_config", + message=StreamingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/notification_message.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/notification_message.py new file mode 100644 index 000000000000..1f389e1deddc --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/notification_message.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 + +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import resource as gcs_resource + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v2", + manifest={ + "NotificationMessage", + }, +) + + +class NotificationMessage(proto.Message): + r"""Cloud SCC's Notification + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + notification_config_name (str): + Name of the notification config that + generated current notification. + finding (google.cloud.securitycenter_v2.types.Finding): + If it's a Finding based notification config, + this field will be populated. + + This field is a member of `oneof`_ ``event``. + resource (google.cloud.securitycenter_v2.types.Resource): + The Cloud resource tied to this + notification's Finding. + """ + + notification_config_name: str = proto.Field( + proto.STRING, + number=1, + ) + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=2, + oneof="event", + message=gcs_finding.Finding, + ) + resource: gcs_resource.Resource = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_resource.Resource, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/org_policy.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/org_policy.py new file mode 100644 index 000000000000..44f04ce0f63e --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/org_policy.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "OrgPolicy", + }, +) + + +class OrgPolicy(proto.Message): + r"""Contains information about the org policies associated with + the finding. + + Attributes: + name (str): + The resource name of the org policy. Example: + "organizations/{organization_id}/policies/{constraint_name}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/process.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/process.py new file mode 100644 index 000000000000..4737d7c9ff06 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/process.py @@ -0,0 +1,135 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 + +from google.cloud.securitycenter_v2.types import file + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v2", + manifest={ + "Process", + "EnvironmentVariable", + }, +) + + +class Process(proto.Message): + r"""Represents an operating system process. + + Attributes: + name (str): + The process name, as displayed in utilities like ``top`` and + ``ps``. This name can be accessed through + ``/proc/[pid]/comm`` and changed with + ``prctl(PR_SET_NAME)``. + binary (google.cloud.securitycenter_v2.types.File): + File information for the process executable. + libraries (MutableSequence[google.cloud.securitycenter_v2.types.File]): + File information for libraries loaded by the + process. + script (google.cloud.securitycenter_v2.types.File): + When the process represents the invocation of a script, + ``binary`` provides information about the interpreter, while + ``script`` provides information about the script file + provided to the interpreter. + args (MutableSequence[str]): + Process arguments as JSON encoded strings. + arguments_truncated (bool): + True if ``args`` is incomplete. + env_variables (MutableSequence[google.cloud.securitycenter_v2.types.EnvironmentVariable]): + Process environment variables. + env_variables_truncated (bool): + True if ``env_variables`` is incomplete. + pid (int): + The process ID. + parent_pid (int): + The parent process ID. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + binary: file.File = proto.Field( + proto.MESSAGE, + number=2, + message=file.File, + ) + libraries: MutableSequence[file.File] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=file.File, + ) + script: file.File = proto.Field( + proto.MESSAGE, + number=4, + message=file.File, + ) + args: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + arguments_truncated: bool = proto.Field( + proto.BOOL, + number=6, + ) + env_variables: MutableSequence["EnvironmentVariable"] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message="EnvironmentVariable", + ) + env_variables_truncated: bool = proto.Field( + proto.BOOL, + number=8, + ) + pid: int = proto.Field( + proto.INT64, + number=9, + ) + parent_pid: int = proto.Field( + proto.INT64, + number=10, + ) + + +class EnvironmentVariable(proto.Message): + r"""A name-value pair representing an environment variable used + in an operating system process. + + Attributes: + name (str): + Environment variable name as a JSON encoded + string. + val (str): + Environment variable value as a JSON encoded + string. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + val: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/resource.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/resource.py new file mode 100644 index 000000000000..2c05d978100b --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/resource.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "Resource", + }, +) + + +class Resource(proto.Message): + r"""Information related to the Google Cloud resource. + + Attributes: + name (str): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + display_name (str): + The human readable name of the resource. + type_ (str): + The full resource type of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + type_: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/resource_value_config.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/resource_value_config.py new file mode 100644 index 000000000000..414ea9982f36 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/resource_value_config.py @@ -0,0 +1,178 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "ResourceValue", + "ResourceValueConfig", + }, +) + + +class ResourceValue(proto.Enum): + r"""Value enum to map to a resource + + Values: + RESOURCE_VALUE_UNSPECIFIED (0): + Unspecific value + HIGH (1): + High resource value + MEDIUM (2): + Medium resource value + LOW (3): + Low resource value + NONE (4): + No resource value, e.g. ignore these + resources + """ + RESOURCE_VALUE_UNSPECIFIED = 0 + HIGH = 1 + MEDIUM = 2 + LOW = 3 + NONE = 4 + + +class ResourceValueConfig(proto.Message): + r"""A resource value config (RVC) is a mapping configuration of + user's resources to resource values. Used in Attack path + simulations. + + Attributes: + name (str): + Name for the resource value config + resource_value (google.cloud.securitycenter_v2.types.ResourceValue): + Resource value level this expression + represents Only required when there is no SDP + mapping in the request + tag_values (MutableSequence[str]): + Required. Tag values combined with AND to check against. + Values in the form "tagValues/123" E.g. [ "tagValues/123", + "tagValues/456", "tagValues/789" ] + https://cloud.google.com/resource-manager/docs/tags/tags-creating-and-managing + resource_type (str): + Apply resource_value only to resources that match + resource_type. resource_type will be checked with "AND" of + other resources. E.g. "storage.googleapis.com/Bucket" with + resource_value "HIGH" will apply "HIGH" value only to + "storage.googleapis.com/Bucket" resources. + scope (str): + Project or folder to scope this config to. + For example, "project/456" would apply this + config only to resources in "project/456" + scope will be checked with "AND" of other + resources. + resource_labels_selector (MutableMapping[str, str]): + List of resource labels to search for, evaluated with AND. + E.g. "resource_labels_selector": {"key": "value", "env": + "prod"} will match resources with labels "key": "value" AND + "env": "prod" + https://cloud.google.com/resource-manager/docs/creating-managing-labels + description (str): + Description of the resource value config. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp this resource value + config was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp this resource value + config was last updated. + sensitive_data_protection_mapping (google.cloud.securitycenter_v2.types.ResourceValueConfig.SensitiveDataProtectionMapping): + A mapping of the sensitivity on Sensitive Data Protection + finding to resource values. This mapping can only be used in + combination with a resource_type that is related to + BigQuery, e.g. "bigquery.googleapis.com/Dataset". + """ + + class SensitiveDataProtectionMapping(proto.Message): + r"""Resource value mapping for Sensitive Data Protection findings If any + of these mappings have a resource value that is not unspecified, the + resource_value field will be ignored when reading this + configuration. + + Attributes: + high_sensitivity_mapping (google.cloud.securitycenter_v2.types.ResourceValue): + Resource value mapping for high-sensitivity + Sensitive Data Protection findings + medium_sensitivity_mapping (google.cloud.securitycenter_v2.types.ResourceValue): + Resource value mapping for medium-sensitivity + Sensitive Data Protection findings + """ + + high_sensitivity_mapping: "ResourceValue" = proto.Field( + proto.ENUM, + number=1, + enum="ResourceValue", + ) + medium_sensitivity_mapping: "ResourceValue" = proto.Field( + proto.ENUM, + number=2, + enum="ResourceValue", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_value: "ResourceValue" = proto.Field( + proto.ENUM, + number=2, + enum="ResourceValue", + ) + tag_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + resource_type: str = proto.Field( + proto.STRING, + number=4, + ) + scope: str = proto.Field( + proto.STRING, + number=5, + ) + resource_labels_selector: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + description: str = proto.Field( + proto.STRING, + number=7, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + sensitive_data_protection_mapping: SensitiveDataProtectionMapping = proto.Field( + proto.MESSAGE, + number=11, + message=SensitiveDataProtectionMapping, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/security_marks.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/security_marks.py new file mode 100644 index 000000000000..38eeb11be6f3 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/security_marks.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "SecurityMarks", + }, +) + + +class SecurityMarks(proto.Message): + r"""User specified security marks that are attached to the parent + Security Command Center resource. Security marks are scoped + within a Security Command Center organization -- they can be + modified and viewed by all users who have proper permissions on + the organization. + + Attributes: + name (str): + The relative resource name of the SecurityMarks. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + The following list shows some examples: + + - ``organizations/{organization_id}/assets/{asset_id}/securityMarks`` + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks`` + marks (MutableMapping[str, str]): + Mutable user specified security marks belonging to the + parent resource. Constraints are as follows: + + - Keys and values are treated as case insensitive + - Keys must be between 1 - 256 characters (inclusive) + - Keys must be letters, numbers, underscores, or dashes + - Values have leading and trailing whitespace trimmed, + remaining characters must be between 1 - 4096 characters + (inclusive) + canonical_name (str): + The canonical name of the marks. The following list shows + some examples: + + - \`organizations/{organization_id}/assets/{asset_id}/securityMarks" + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks" +``\ organizations/{organization_id}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks" + + - \`folders/{folder_id}/assets/{asset_id}/securityMarks" + - + + ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks" +``\ folders/{folder_id}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks" + + - \`projects/{project_number}/assets/{asset_id}/securityMarks" + - + + ``projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks" +``\ projects/{project_number}/sources/{source_id}/locations/{location}/findings/{finding_id}/securityMarks". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + marks: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/security_posture.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/security_posture.py new file mode 100644 index 000000000000..4ee2430010ae --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/security_posture.py @@ -0,0 +1,127 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "SecurityPosture", + }, +) + + +class SecurityPosture(proto.Message): + r"""Represents a posture that is deployed on Google Cloud by the + Security Command Center Posture Management service. A posture + contains one or more policy sets. A policy set is a group of + policies that enforce a set of security rules on Google Cloud. + + Attributes: + name (str): + Name of the posture, for example, ``CIS-Posture``. + revision_id (str): + The version of the posture, for example, ``c7cfa2a8``. + posture_deployment_resource (str): + The project, folder, or organization on which the posture is + deployed, for example, ``projects/{project_number}``. + posture_deployment (str): + The name of the posture deployment, for example, + ``organizations/{org_id}/posturedeployments/{posture_deployment_id}``. + changed_policy (str): + The name of the updated policy, for example, + ``projects/{project_id}/policies/{constraint_name}``. + policy_set (str): + The name of the updated policy set, for example, + ``cis-policyset``. + policy (str): + The ID of the updated policy, for example, + ``compute-policy-1``. + policy_drift_details (MutableSequence[google.cloud.securitycenter_v2.types.SecurityPosture.PolicyDriftDetails]): + The details about a change in an updated + policy that violates the deployed posture. + """ + + class PolicyDriftDetails(proto.Message): + r"""The policy field that violates the deployed posture and its + expected and detected values. + + Attributes: + field (str): + The name of the updated field, for example + constraint.implementation.policy_rules[0].enforce + expected_value (str): + The value of this field that was configured in a posture, + for example, ``true`` or + ``allowed_values={"projects/29831892"}``. + detected_value (str): + The detected value that violates the deployed posture, for + example, ``false`` or + ``allowed_values={"projects/22831892"}``. + """ + + field: str = proto.Field( + proto.STRING, + number=1, + ) + expected_value: str = proto.Field( + proto.STRING, + number=2, + ) + detected_value: str = proto.Field( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + revision_id: str = proto.Field( + proto.STRING, + number=2, + ) + posture_deployment_resource: str = proto.Field( + proto.STRING, + number=3, + ) + posture_deployment: str = proto.Field( + proto.STRING, + number=4, + ) + changed_policy: str = proto.Field( + proto.STRING, + number=5, + ) + policy_set: str = proto.Field( + proto.STRING, + number=6, + ) + policy: str = proto.Field( + proto.STRING, + number=7, + ) + policy_drift_details: MutableSequence[PolicyDriftDetails] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=PolicyDriftDetails, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/securitycenter_service.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/securitycenter_service.py new file mode 100644 index 000000000000..f5465ae463ed --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/securitycenter_service.py @@ -0,0 +1,1838 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v2.types import ( + resource_value_config as gcs_resource_value_config, +) +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import attack_path, bigquery_export +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v2", + manifest={ + "BatchCreateResourceValueConfigsRequest", + "BatchCreateResourceValueConfigsResponse", + "BulkMuteFindingsRequest", + "BulkMuteFindingsResponse", + "CreateBigQueryExportRequest", + "CreateFindingRequest", + "CreateMuteConfigRequest", + "CreateNotificationConfigRequest", + "CreateResourceValueConfigRequest", + "CreateSourceRequest", + "DeleteBigQueryExportRequest", + "DeleteMuteConfigRequest", + "DeleteNotificationConfigRequest", + "DeleteResourceValueConfigRequest", + "GetBigQueryExportRequest", + "GetMuteConfigRequest", + "GetNotificationConfigRequest", + "GetResourceValueConfigRequest", + "GetSourceRequest", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "ListAttackPathsRequest", + "ListAttackPathsResponse", + "GetSimulationRequest", + "GetValuedResourceRequest", + "ListBigQueryExportsRequest", + "ListBigQueryExportsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "ListMuteConfigsRequest", + "ListMuteConfigsResponse", + "ListNotificationConfigsRequest", + "ListNotificationConfigsResponse", + "ListResourceValueConfigsRequest", + "ListResourceValueConfigsResponse", + "ListSourcesRequest", + "ListSourcesResponse", + "ListValuedResourcesRequest", + "ListValuedResourcesResponse", + "SetFindingStateRequest", + "SetMuteRequest", + "UpdateBigQueryExportRequest", + "UpdateExternalSystemRequest", + "UpdateFindingRequest", + "UpdateMuteConfigRequest", + "UpdateNotificationConfigRequest", + "UpdateResourceValueConfigRequest", + "UpdateSecurityMarksRequest", + "UpdateSourceRequest", + }, +) + + +class BatchCreateResourceValueConfigsRequest(proto.Message): + r"""Request message to create multiple resource value configs + + Attributes: + parent (str): + Required. Resource name of the new + ResourceValueConfig's parent. The parent field + in the CreateResourceValueConfigRequest messages + must either be empty or match this field. + requests (MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]): + Required. The resource value configs to be + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence["CreateResourceValueConfigRequest"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="CreateResourceValueConfigRequest", + ) + + +class BatchCreateResourceValueConfigsResponse(proto.Message): + r"""Response message for BatchCreateResourceValueConfigs + + Attributes: + resource_value_configs (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfig]): + The resource value configs created + """ + + resource_value_configs: MutableSequence[ + gcs_resource_value_config.ResourceValueConfig + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_resource_value_config.ResourceValueConfig, + ) + + +class BulkMuteFindingsRequest(proto.Message): + r"""Request message for bulk findings update. + + Note: + + 1. If multiple bulk update requests match the same resource, the + order in which they get executed is not defined. + 2. Once a bulk operation is started, there is no way to stop it. + + Attributes: + parent (str): + Required. The parent, at which bulk action needs to be + applied. If no location is specified, findings are updated + in global. The following list shows some examples: + + - ``organizations/[organization_id]`` + - ``organizations/[organization_id]/locations/[location_id]`` + - ``folders/[folder_id]`` + - ``folders/[folder_id]/locations/[location_id]`` + - ``projects/[project_id]`` + - ``projects/[project_id]/locations/[location_id]`` + filter (str): + Expression that identifies findings that should be updated. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + + +class BulkMuteFindingsResponse(proto.Message): + r"""The response to a BulkMute request. Contains the LRO + information. + + """ + + +class CreateBigQueryExportRequest(proto.Message): + r"""Request message for creating a BigQuery export. + + Attributes: + parent (str): + Required. The name of the parent resource of the new + BigQuery export. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): + Required. The BigQuery export being created. + big_query_export_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must consist + of only lowercase letters, numbers, and hyphens, + must start with a letter, must end with either a + letter or a number, and must be 63 characters or + less. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + big_query_export: bigquery_export.BigQueryExport = proto.Field( + proto.MESSAGE, + number=2, + message=bigquery_export.BigQueryExport, + ) + big_query_export_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class CreateFindingRequest(proto.Message): + r"""Request message for creating a finding. + + Attributes: + parent (str): + Required. Resource name of the new finding's parent. The + following list shows some examples of the format: + + ``organizations/[organization_id]/sources/[source_id]`` + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + finding_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must be + alphanumeric and less than or equal to 32 + characters and greater than 0 characters in + length. + finding (google.cloud.securitycenter_v2.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output only + fields on this resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + finding_id: str = proto.Field( + proto.STRING, + number=2, + ) + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_finding.Finding, + ) + + +class CreateMuteConfigRequest(proto.Message): + r"""Request message for creating a mute config. + + Attributes: + parent (str): + Required. Resource name of the new mute configs's parent. + Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + mute_config (google.cloud.securitycenter_v2.types.MuteConfig): + Required. The mute config being created. + mute_config_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must consist + of only lowercase letters, numbers, and hyphens, + must start with a letter, must end with either a + letter or a number, and must be 63 characters or + less. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + mute_config: gcs_mute_config.MuteConfig = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_mute_config.MuteConfig, + ) + mute_config_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class CreateNotificationConfigRequest(proto.Message): + r"""Request message for creating a notification config. + + Attributes: + parent (str): + Required. Resource name of the new notification config's + parent. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + config_id (str): + Required. + Unique identifier provided by the client within + the parent scope. It must be between 1 and 128 + characters and contain alphanumeric characters, + underscores, or hyphens only. + notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): + Required. The notification config being + created. The name and the service account will + be ignored as they are both output only fields + on this resource. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + config_id: str = proto.Field( + proto.STRING, + number=2, + ) + notification_config: gcs_notification_config.NotificationConfig = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_notification_config.NotificationConfig, + ) + + +class CreateResourceValueConfigRequest(proto.Message): + r"""Request message to create single resource value config + + Attributes: + parent (str): + Required. Resource name of the new + ResourceValueConfig's parent. + resource_value_config (google.cloud.securitycenter_v2.types.ResourceValueConfig): + Required. The resource value config being + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_resource_value_config.ResourceValueConfig, + ) + + +class CreateSourceRequest(proto.Message): + r"""Request message for creating a source. + + Attributes: + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + source (google.cloud.securitycenter_v2.types.Source): + Required. The Source being created, only the display_name + and description will be used. All other fields will be + ignored. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_source.Source, + ) + + +class DeleteBigQueryExportRequest(proto.Message): + r"""Request message for deleting a BigQuery export. + + Attributes: + name (str): + Required. The name of the BigQuery export to delete. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}/locations/{location}/bigQueryExports/{export_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteMuteConfigRequest(proto.Message): + r"""Request message for deleting a mute config. If no location is + specified, default is global. + + Attributes: + name (str): + Required. Name of the mute config to delete. The following + list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteNotificationConfigRequest(proto.Message): + r"""Request message for deleting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to delete. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]notificationConfigs/[config_id]`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteResourceValueConfigRequest(proto.Message): + r"""Request message to delete resource value config + + Attributes: + name (str): + Required. Name of the ResourceValueConfig to + delete + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetBigQueryExportRequest(proto.Message): + r"""Request message for retrieving a BigQuery export. + + Attributes: + name (str): + Required. Name of the BigQuery export to retrieve. The + following list shows some examples of the format: + + - + + ``organizations/{organization}/locations/{location}/bigQueryExports/{export_id}`` + + - ``folders/{folder}/locations/{location}/bigQueryExports/{export_id}`` + - ``projects/{project}locations/{location}//bigQueryExports/{export_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetMuteConfigRequest(proto.Message): + r"""Request message for retrieving a mute config. If no location + is specified, default is global. + + Attributes: + name (str): + Required. Name of the mute config to retrieve. The following + list shows some examples of the format: + + - ``organizations/{organization}/muteConfigs/{config_id}`` + - + + ``organizations/{organization}/locations/{location}/muteConfigs/{config_id}`` + + - ``folders/{folder}/muteConfigs/{config_id}`` + - ``folders/{folder}/locations/{location}/muteConfigs/{config_id}`` + - ``projects/{project}/muteConfigs/{config_id}`` + - ``projects/{project}/locations/{location}/muteConfigs/{config_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetNotificationConfigRequest(proto.Message): + r"""Request message for getting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to get. The + following list shows some examples of the format: + + - + + ``organizations/[organization_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``folders/[folder_id]/locations/[location_id]/notificationConfigs/[config_id]`` + + + ``projects/[project_id]/locations/[location_id]/notificationConfigs/[config_id]`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetResourceValueConfigRequest(proto.Message): + r"""Request message to get resource value config + + Attributes: + name (str): + Required. Name of the resource value config to retrieve. Its + format is + organizations/{organization}/resourceValueConfigs/{config_id}. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSourceRequest(proto.Message): + r"""Request message for getting a source. + + Attributes: + name (str): + Required. Relative resource name of the source. Its format + is "organizations/[organization_id]/source/[source_id]". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GroupFindingsRequest(proto.Message): + r"""Request message for grouping by findings. + + Attributes: + parent (str): + Required. Name of the source to groupBy. If no location is + specified, finding is assumed to be in global. The following + list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To groupBy across all sources provide a source_id of ``-``. + The following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/[location_id]`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-/locations/[location_id]`` + - ``projects/{project_id}/sources/-`` + - ``projects/{project_id}/sources/-/locations/[location_id]`` + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - severity: ``=``, ``:`` + + - security_marks.marks: ``=``, ``:`` + + - resource: + + - resource.name: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping. The string value should follow SQL syntax: + comma separated list of fields. For example: + "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + - severity + page_token (str): + The value returned by the last ``GroupFindingsResponse``; + indicates that this is a continuation of a prior + ``GroupFindings`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + group_by: str = proto.Field( + proto.STRING, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=7, + ) + page_size: int = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupFindingsResponse(proto.Message): + r"""Response message for group by findings. + + Attributes: + group_by_results (MutableSequence[google.cloud.securitycenter_v2.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results: MutableSequence["GroupResult"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="GroupResult", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class GroupResult(proto.Message): + r"""Result containing the properties and count of a groupBy + request. + + Attributes: + properties (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Properties matching the groupBy fields in the + request. + count (int): + Total count of resources for the given + properties. + """ + + properties: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=struct_pb2.Value, + ) + count: int = proto.Field( + proto.INT64, + number=2, + ) + + +class ListAttackPathsRequest(proto.Message): + r"""Request message for listing the attack paths for a given + simulation or valued resource. + + Attributes: + parent (str): + Required. Name of parent to list attack paths. + + Valid formats: "organizations/{organization}", + "organizations/{organization}/simulations/{simulation}" + "organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}" + "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}". + filter (str): + The filter expression that filters the attack path in the + response. Supported fields: + + - ``valued_resources`` supports = + page_token (str): + The value returned by the last ``ListAttackPathsResponse``; + indicates that this is a continuation of a prior + ``ListAttackPaths`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class ListAttackPathsResponse(proto.Message): + r"""Response message for listing the attack paths for a given + simulation or valued resource. + + Attributes: + attack_paths (MutableSequence[google.cloud.securitycenter_v2.types.AttackPath]): + The attack paths that the attack path + simulation identified. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + attack_paths: MutableSequence[attack_path.AttackPath] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=attack_path.AttackPath, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetSimulationRequest(proto.Message): + r"""Request message for getting simulation. + Simulation name can include "latest" to retrieve the latest + simulation For example, "organizations/123/simulations/latest" + + Attributes: + name (str): + Required. The organization name or simulation + name of this simulation + Valid format: + + "organizations/{organization}/simulations/latest" + "organizations/{organization}/simulations/{simulation}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetValuedResourceRequest(proto.Message): + r"""Request message for getting a valued resource. + + Attributes: + name (str): + Required. The name of this valued resource + + Valid format: + "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListBigQueryExportsRequest(proto.Message): + r"""Request message for listing BigQuery exports at a given scope + e.g. organization, folder or project. + + Attributes: + parent (str): + Required. The parent, which owns the collection of BigQuery + exports. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + page_size (int): + The maximum number of configs to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous + ``ListBigQueryExports`` call. Provide this to retrieve the + subsequent page. When paginating, all other parameters + provided to ``ListBigQueryExports`` must match the 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 ListBigQueryExportsResponse(proto.Message): + r"""Response message for listing BigQuery exports. + + Attributes: + big_query_exports (MutableSequence[google.cloud.securitycenter_v2.types.BigQueryExport]): + The BigQuery exports from the specified + parent. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + big_query_exports: MutableSequence[ + bigquery_export.BigQueryExport + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=bigquery_export.BigQueryExport, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request message for listing findings. + + Attributes: + parent (str): + Required. Name of the source the findings belong to. If no + location is specified, the default is global. The following + list shows some examples: + + - ``organizations/[organization_id]/sources/[source_id]`` + - + + ``organizations/[organization_id]/sources/[source_id]/locations/[location_id]`` + + - ``folders/[folder_id]/sources/[source_id]`` + - ``folders/[folder_id]/sources/[source_id]/locations/[location_id]`` + - ``projects/[project_id]/sources/[source_id]`` + - ``projects/[project_id]/sources/[source_id]/locations/[location_id]`` + + To list across all sources provide a source_id of ``-``. The + following list shows some examples: + + - ``organizations/{organization_id}/sources/-`` + - ``organizations/{organization_id}/sources/-/locations/{location_id}`` + - ``folders/{folder_id}/sources/-`` + - ``folders/{folder_id}/sources/-locations/{location_id}`` + - ``projects/{projects_id}/sources/-`` + - ``projects/{projects_id}/sources/-/locations/{location_id}`` + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - severity: ``=``, ``:`` + + - security_marks.marks: ``=``, ``:`` + + - resource: + + - resource.name: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + - resource.folders.resource_folder: ``=``, ``:`` + - resource.display_name: ``=``, ``:`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: "name,parent". The + default sorting order is ascending. To specify descending + order for a field, a suffix " desc" should be appended to + the field name. For example: "name desc,parent". Redundant + space characters in the syntax are insignificant. "name + desc,parent" and " name desc , parent " are equivalent. + + The following fields are supported: name parent state + category resource_name event_time security_marks.marks + field_mask (google.protobuf.field_mask_pb2.FieldMask): + A field mask to specify the Finding fields to + be listed in the response. An empty field mask + will list all fields. + page_token (str): + The value returned by the last ``ListFindingsResponse``; + indicates that this is a continuation of a prior + ``ListFindings`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + order_by: str = proto.Field( + proto.STRING, + number=3, + ) + field_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token: str = proto.Field( + proto.STRING, + number=8, + ) + page_size: int = proto.Field( + proto.INT32, + number=9, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response message for listing findings. + + Attributes: + list_findings_results (MutableSequence[google.cloud.securitycenter_v2.types.ListFindingsResponse.ListFindingsResult]): + Findings matching the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of findings matching the + query. + """ + + class ListFindingsResult(proto.Message): + r"""Result containing the Finding. + + Attributes: + finding (google.cloud.securitycenter_v2.types.Finding): + Finding matching the search request. + resource (google.cloud.securitycenter_v2.types.ListFindingsResponse.ListFindingsResult.Resource): + Output only. Resource that is associated with + this finding. + """ + + class Resource(proto.Message): + r"""Information related to the Google Cloud resource that is + associated with this finding. + + Attributes: + name (str): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + display_name (str): + The human readable name of the resource. + type_ (str): + The full resource type of the resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + type_: str = proto.Field( + proto.STRING, + number=3, + ) + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + resource: "ListFindingsResponse.ListFindingsResult.Resource" = proto.Field( + proto.MESSAGE, + number=3, + message="ListFindingsResponse.ListFindingsResult.Resource", + ) + + @property + def raw_page(self): + return self + + list_findings_results: MutableSequence[ListFindingsResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListFindingsResult, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class ListMuteConfigsRequest(proto.Message): + r"""Request message for listing mute configs at a given scope + e.g. organization, folder or project. If no location is + specified, default is global. + + Attributes: + parent (str): + Required. The parent, which owns the collection of mute + configs. Its format is "organizations/[organization_id]", + "folders/[folder_id]", "projects/[project_id]", + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", + "projects/[project_id]/locations/[location_id]". + page_size (int): + The maximum number of configs to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous ``ListMuteConfigs`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListMuteConfigs`` must match the 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 ListMuteConfigsResponse(proto.Message): + r"""Response message for listing mute configs. + + Attributes: + mute_configs (MutableSequence[google.cloud.securitycenter_v2.types.MuteConfig]): + The mute configs from the specified parent. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + mute_configs: MutableSequence[gcs_mute_config.MuteConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_mute_config.MuteConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListNotificationConfigsRequest(proto.Message): + r"""Request message for listing notification configs. + + Attributes: + parent (str): + Required. The name of the parent in which to list the + notification configurations. Its format is + "organizations/[organization_id]/locations/[location_id]", + "folders/[folder_id]/locations/[location_id]", or + "projects/[project_id]/locations/[location_id]". + page_token (str): + The value returned by the last + ``ListNotificationConfigsResponse``; indicates that this is + a continuation of a prior ``ListNotificationConfigs`` call, + and that the system should return the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListNotificationConfigsResponse(proto.Message): + r"""Response message for listing notification configs. + + Attributes: + notification_configs (MutableSequence[google.cloud.securitycenter_v2.types.NotificationConfig]): + Notification configs belonging to the + requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + notification_configs: MutableSequence[ + gcs_notification_config.NotificationConfig + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListResourceValueConfigsRequest(proto.Message): + r"""Request message to list resource value configs of a parent + + Attributes: + parent (str): + Required. The parent, which owns the collection of resource + value configs. Its format is + "organizations/[organization_id]". + page_size (int): + The maximum number of configs to return. The + service may return fewer than this value. + If unspecified, at most 10 configs will be + returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + A page token, received from a previous + ``ListResourceValueConfigs`` call. Provide this to retrieve + the subsequent page. + + When paginating, all other parameters provided to + ``ListResourceValueConfigs`` must match the call that + provided the page token. + + page_size can be specified, and the new page_size will be + used. + """ + + 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 ListResourceValueConfigsResponse(proto.Message): + r"""Response message to list resource value configs + + Attributes: + resource_value_configs (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfig]): + The resource value configs from the specified + parent. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is empty, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + resource_value_configs: MutableSequence[ + gcs_resource_value_config.ResourceValueConfig + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_resource_value_config.ResourceValueConfig, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSourcesRequest(proto.Message): + r"""Request message for listing sources. + + Attributes: + parent (str): + Required. Resource name of the parent of sources to list. + Its format should be "organizations/[organization_id]", + "folders/[folder_id]", or "projects/[project_id]". + page_token (str): + The value returned by the last ``ListSourcesResponse``; + indicates that this is a continuation of a prior + ``ListSources`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=7, + ) + + +class ListSourcesResponse(proto.Message): + r"""Response message for listing sources. + + Attributes: + sources (MutableSequence[google.cloud.securitycenter_v2.types.Source]): + Sources belonging to the requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + sources: MutableSequence[gcs_source.Source] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListValuedResourcesRequest(proto.Message): + r"""Request message for listing the valued resources for a given + simulation. + + Attributes: + parent (str): + Required. Name of parent to list exposed resources. + + Valid formats: "organizations/{organization}", + "organizations/{organization}/simulations/{simulation}" + "organizations/{organization}/simulations/{simulation}/attackExposureResults/{attack_exposure_result_v2}". + filter (str): + The filter expression that filters the valued resources in + the response. Supported fields: + + - ``resource_value`` supports = + - ``resource_type`` supports = + page_token (str): + The value returned by the last + ``ListValuedResourcesResponse``; indicates that this is a + continuation of a prior ``ListValuedResources`` call, and + that the system should return the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + order_by (str): + Optional. The fields by which to order the valued resources + response. + + Supported fields: + + - ``exposed_score`` + + - ``resource_value`` + + - ``resource_type`` + + Values should be a comma separated list of fields. For + example: ``exposed_score,resource_value``. + + The default sorting order is descending. To specify + ascending or descending order for a field, append a " ASC" + or a " DESC" suffix, respectively; for example: + ``exposed_score DESC``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListValuedResourcesResponse(proto.Message): + r"""Response message for listing the valued resources for a given + simulation. + + Attributes: + valued_resources (MutableSequence[google.cloud.securitycenter_v2.types.ValuedResource]): + The valued resources that the attack path + simulation identified. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The estimated total number of results + matching the query. + """ + + @property + def raw_page(self): + return self + + valued_resources: MutableSequence[ + valued_resource.ValuedResource + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=valued_resource.ValuedResource, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class SetFindingStateRequest(proto.Message): + r"""Request message for updating a finding's state. + + Attributes: + name (str): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + state (google.cloud.securitycenter_v2.types.Finding.State): + Required. The desired State of the finding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: gcs_finding.Finding.State = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.State, + ) + + +class SetMuteRequest(proto.Message): + r"""Request message for updating a finding's mute status. + + Attributes: + name (str): + Required. The `relative resource + name `__ + of the finding. If no location is specified, finding is + assumed to be in global. The following list shows some + examples: + + - + + ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}`` + + + ``organizations/{organization_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``folders/{folder_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``folders/{folder_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + + - ``projects/{project_id}/sources/{source_id}/findings/{finding_id}`` + - + + ``projects/{project_id}/sources/{source_id}/locations/{location_id}/findings/{finding_id}`` + mute (google.cloud.securitycenter_v2.types.Finding.Mute): + Required. The desired state of the Mute. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + mute: gcs_finding.Finding.Mute = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.Mute, + ) + + +class UpdateBigQueryExportRequest(proto.Message): + r"""Request message for updating a BigQuery export. + + Attributes: + big_query_export (google.cloud.securitycenter_v2.types.BigQueryExport): + Required. The BigQuery export being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be updated. + """ + + big_query_export: bigquery_export.BigQueryExport = proto.Field( + proto.MESSAGE, + number=1, + message=bigquery_export.BigQueryExport, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateExternalSystemRequest(proto.Message): + r"""Request message for updating a ExternalSystem resource. + + Attributes: + external_system (google.cloud.securitycenter_v2.types.ExternalSystem): + Required. The external system resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + external system resource. + If empty all mutable fields will be updated. + """ + + external_system: gcs_external_system.ExternalSystem = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_external_system.ExternalSystem, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateFindingRequest(proto.Message): + r"""Request message for updating or creating a finding. + + Attributes: + finding (google.cloud.securitycenter_v2.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the name + must be alphanumeric and less than or equal to 32 characters + and greater than 0 characters in length. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing source_properties. + Individual source_properties can be added/updated by using + "source_properties." in the field mask. + """ + + finding: gcs_finding.Finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateMuteConfigRequest(proto.Message): + r"""Request message for updating a mute config. + + Attributes: + mute_config (google.cloud.securitycenter_v2.types.MuteConfig): + Required. The mute config being updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be updated. + """ + + mute_config: gcs_mute_config.MuteConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_mute_config.MuteConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateNotificationConfigRequest(proto.Message): + r"""Request message for updating a notification config. + + Attributes: + notification_config (google.cloud.securitycenter_v2.types.NotificationConfig): + Required. The notification config to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + notification config. + If empty all mutable fields will be updated. + """ + + notification_config: gcs_notification_config.NotificationConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateResourceValueConfigRequest(proto.Message): + r"""Request message to update resource value config + + Attributes: + resource_value_config (google.cloud.securitycenter_v2.types.ResourceValueConfig): + Required. The resource value config being + updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. + If empty all mutable fields will be updated. + """ + + resource_value_config: gcs_resource_value_config.ResourceValueConfig = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_resource_value_config.ResourceValueConfig, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + + Attributes: + security_marks (google.cloud.securitycenter_v2.types.SecurityMarks): + Required. The security marks resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If empty + or set to "marks", all marks will be replaced. Individual + marks can be updated using "marks.". + """ + + security_marks: gcs_security_marks.SecurityMarks = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_security_marks.SecurityMarks, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + + Attributes: + source (google.cloud.securitycenter_v2.types.Source): + Required. The source resource to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the source + resource. + If empty all mutable fields will be updated. + """ + + source: gcs_source.Source = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/simulation.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/simulation.py new file mode 100644 index 000000000000..495fa2590c3a --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/simulation.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter_v2.types import valued_resource + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v2", + manifest={ + "Simulation", + }, +) + + +class Simulation(proto.Message): + r"""Attack path simulation + + Attributes: + name (str): + Full resource name of the Simulation: + + organizations/123/simulations/456 + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time simulation was created + resource_value_configs_metadata (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfigMetadata]): + Resource value configurations' metadata used + in this simulation. Maximum of 100. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + resource_value_configs_metadata: MutableSequence[ + valued_resource.ResourceValueConfigMetadata + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=valued_resource.ResourceValueConfigMetadata, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/source.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/source.py new file mode 100644 index 000000000000..e1dc3b2592c9 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/source.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "Source", + }, +) + + +class Source(proto.Message): + r"""Security Command Center finding source. A finding source + is an entity or a mechanism that can produce a finding. A source + is like a container of findings that come from the same scanner, + logger, monitor, and other tools. + + Attributes: + name (str): + The relative resource name of this source. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}". + display_name (str): + The source's display name. + A source's display name must be unique amongst + its siblings, for example, two sources with the + same parent can't share the same display name. + The display name must have a length between 1 + and 64 characters (inclusive). + description (str): + The description of the source (max of 1024 + characters). Example: + + "Web Security Scanner is a web security scanner + for common vulnerabilities in App Engine + applications. It can automatically scan and + detect four common vulnerabilities, including + cross-site-scripting (XSS), Flash injection, + mixed content (HTTP in HTTPS), and outdated or + insecure libraries.". + canonical_name (str): + The canonical name of the finding source. It's either + "organizations/{organization_id}/sources/{source_id}", + "folders/{folder_id}/sources/{source_id}", or + "projects/{project_number}/sources/{source_id}", depending + on the closest CRM ancestor of the resource associated with + the finding. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + canonical_name: str = proto.Field( + proto.STRING, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/valued_resource.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/valued_resource.py new file mode 100644 index 000000000000..0f347496e1a9 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/valued_resource.py @@ -0,0 +1,128 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "ValuedResource", + "ResourceValueConfigMetadata", + }, +) + + +class ValuedResource(proto.Message): + r"""A resource that is determined to have value to a user's + system + + Attributes: + name (str): + Valued resource name, for example, e.g.: + ``organizations/123/simulations/456/valuedResources/789`` + resource (str): + The `full resource + name `__ + of the valued resource. + resource_type (str): + The `resource + type `__ + of the valued resource. + display_name (str): + Human-readable name of the valued resource. + resource_value (google.cloud.securitycenter_v2.types.ValuedResource.ResourceValue): + How valuable this resource is. + exposed_score (float): + Exposed score for this valued resource. A + value of 0 means no exposure was detected + exposure. + resource_value_configs_used (MutableSequence[google.cloud.securitycenter_v2.types.ResourceValueConfigMetadata]): + List of resource value configurations' + metadata used to determine the value of this + resource. Maximum of 100. + """ + + class ResourceValue(proto.Enum): + r"""How valuable the resource is. + + Values: + RESOURCE_VALUE_UNSPECIFIED (0): + The resource value isn't specified. + RESOURCE_VALUE_LOW (1): + This is a low-value resource. + RESOURCE_VALUE_MEDIUM (2): + This is a medium-value resource. + RESOURCE_VALUE_HIGH (3): + This is a high-value resource. + """ + RESOURCE_VALUE_UNSPECIFIED = 0 + RESOURCE_VALUE_LOW = 1 + RESOURCE_VALUE_MEDIUM = 2 + RESOURCE_VALUE_HIGH = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource: str = proto.Field( + proto.STRING, + number=2, + ) + resource_type: str = proto.Field( + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + resource_value: ResourceValue = proto.Field( + proto.ENUM, + number=5, + enum=ResourceValue, + ) + exposed_score: float = proto.Field( + proto.DOUBLE, + number=6, + ) + resource_value_configs_used: MutableSequence[ + "ResourceValueConfigMetadata" + ] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message="ResourceValueConfigMetadata", + ) + + +class ResourceValueConfigMetadata(proto.Message): + r"""Metadata about a ResourceValueConfig. For example, id and + name. + + Attributes: + name (str): + Resource value config name + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/vulnerability.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/vulnerability.py new file mode 100644 index 000000000000..dd04b11ce728 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/vulnerability.py @@ -0,0 +1,538 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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.securitycenter.v2", + manifest={ + "Vulnerability", + "Cve", + "Reference", + "Cvssv3", + "Package", + "SecurityBulletin", + }, +) + + +class Vulnerability(proto.Message): + r"""Refers to common vulnerability fields e.g. cve, cvss, cwe + etc. + + Attributes: + cve (google.cloud.securitycenter_v2.types.Cve): + CVE stands for Common Vulnerabilities and + Exposures (https://cve.mitre.org/about/) + offending_package (google.cloud.securitycenter_v2.types.Package): + The offending package is relevant to the + finding. + fixed_package (google.cloud.securitycenter_v2.types.Package): + The fixed package is relevant to the finding. + security_bulletin (google.cloud.securitycenter_v2.types.SecurityBulletin): + The security bulletin is relevant to this + finding. + """ + + cve: "Cve" = proto.Field( + proto.MESSAGE, + number=1, + message="Cve", + ) + offending_package: "Package" = proto.Field( + proto.MESSAGE, + number=2, + message="Package", + ) + fixed_package: "Package" = proto.Field( + proto.MESSAGE, + number=3, + message="Package", + ) + security_bulletin: "SecurityBulletin" = proto.Field( + proto.MESSAGE, + number=4, + message="SecurityBulletin", + ) + + +class Cve(proto.Message): + r"""CVE stands for Common Vulnerabilities and Exposures. Information + from the `CVE + record `__ that + describes this vulnerability. + + Attributes: + id (str): + The unique identifier for the vulnerability. + e.g. CVE-2021-34527 + references (MutableSequence[google.cloud.securitycenter_v2.types.Reference]): + Additional information about the CVE. + e.g. + https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527 + cvssv3 (google.cloud.securitycenter_v2.types.Cvssv3): + Describe Common Vulnerability Scoring System + specified at + https://www.first.org/cvss/v3.1/specification-document + upstream_fix_available (bool): + Whether upstream fix is available for the + CVE. + impact (google.cloud.securitycenter_v2.types.Cve.RiskRating): + The potential impact of the vulnerability if + it was to be exploited. + exploitation_activity (google.cloud.securitycenter_v2.types.Cve.ExploitationActivity): + The exploitation activity of the + vulnerability in the wild. + observed_in_the_wild (bool): + Whether or not the vulnerability has been + observed in the wild. + zero_day (bool): + Whether or not the vulnerability was zero day + when the finding was published. + """ + + class RiskRating(proto.Enum): + r"""The possible values of impact of the vulnerability if it was + to be exploited. + + Values: + RISK_RATING_UNSPECIFIED (0): + Invalid or empty value. + LOW (1): + Exploitation would have little to no security + impact. + MEDIUM (2): + Exploitation would enable attackers to + perform activities, or could allow attackers to + have a direct impact, but would require + additional steps. + HIGH (3): + Exploitation would enable attackers to have a + notable direct impact without needing to + overcome any major mitigating factors. + CRITICAL (4): + Exploitation would fundamentally undermine + the security of affected systems, enable actors + to perform significant attacks with minimal + effort, with little to no mitigating factors to + overcome. + """ + RISK_RATING_UNSPECIFIED = 0 + LOW = 1 + MEDIUM = 2 + HIGH = 3 + CRITICAL = 4 + + class ExploitationActivity(proto.Enum): + r"""The possible values of exploitation activity of the + vulnerability in the wild. + + Values: + EXPLOITATION_ACTIVITY_UNSPECIFIED (0): + Invalid or empty value. + WIDE (1): + Exploitation has been reported or confirmed + to widely occur. + CONFIRMED (2): + Limited reported or confirmed exploitation + activities. + AVAILABLE (3): + Exploit is publicly available. + ANTICIPATED (4): + No known exploitation activity, but has a + high potential for exploitation. + NO_KNOWN (5): + No known exploitation activity. + """ + EXPLOITATION_ACTIVITY_UNSPECIFIED = 0 + WIDE = 1 + CONFIRMED = 2 + AVAILABLE = 3 + ANTICIPATED = 4 + NO_KNOWN = 5 + + id: str = proto.Field( + proto.STRING, + number=1, + ) + references: MutableSequence["Reference"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Reference", + ) + cvssv3: "Cvssv3" = proto.Field( + proto.MESSAGE, + number=3, + message="Cvssv3", + ) + upstream_fix_available: bool = proto.Field( + proto.BOOL, + number=4, + ) + impact: RiskRating = proto.Field( + proto.ENUM, + number=5, + enum=RiskRating, + ) + exploitation_activity: ExploitationActivity = proto.Field( + proto.ENUM, + number=6, + enum=ExploitationActivity, + ) + observed_in_the_wild: bool = proto.Field( + proto.BOOL, + number=7, + ) + zero_day: bool = proto.Field( + proto.BOOL, + number=8, + ) + + +class Reference(proto.Message): + r"""Additional Links + + Attributes: + source (str): + Source of the reference e.g. NVD + uri (str): + Uri for the mentioned source e.g. + https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527. + """ + + source: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Cvssv3(proto.Message): + r"""Common Vulnerability Scoring System version 3. + + Attributes: + base_score (float): + The base score is a function of the base + metric scores. + attack_vector (google.cloud.securitycenter_v2.types.Cvssv3.AttackVector): + Base Metrics + Represents the intrinsic characteristics of a + vulnerability that are constant over time and + across user environments. This metric reflects + the context by which vulnerability exploitation + is possible. + attack_complexity (google.cloud.securitycenter_v2.types.Cvssv3.AttackComplexity): + This metric describes the conditions beyond + the attacker's control that must exist in order + to exploit the vulnerability. + privileges_required (google.cloud.securitycenter_v2.types.Cvssv3.PrivilegesRequired): + This metric describes the level of privileges + an attacker must possess before successfully + exploiting the vulnerability. + user_interaction (google.cloud.securitycenter_v2.types.Cvssv3.UserInteraction): + This metric captures the requirement for a + human user, other than the attacker, to + participate in the successful compromise of the + vulnerable component. + scope (google.cloud.securitycenter_v2.types.Cvssv3.Scope): + The Scope metric captures whether a + vulnerability in one vulnerable component + impacts resources in components beyond its + security scope. + confidentiality_impact (google.cloud.securitycenter_v2.types.Cvssv3.Impact): + This metric measures the impact to the + confidentiality of the information resources + managed by a software component due to a + successfully exploited vulnerability. + integrity_impact (google.cloud.securitycenter_v2.types.Cvssv3.Impact): + This metric measures the impact to integrity + of a successfully exploited vulnerability. + availability_impact (google.cloud.securitycenter_v2.types.Cvssv3.Impact): + This metric measures the impact to the + availability of the impacted component resulting + from a successfully exploited vulnerability. + """ + + class AttackVector(proto.Enum): + r"""This metric reflects the context by which vulnerability + exploitation is possible. + + Values: + ATTACK_VECTOR_UNSPECIFIED (0): + Invalid value. + ATTACK_VECTOR_NETWORK (1): + The vulnerable component is bound to the + network stack and the set of possible attackers + extends beyond the other options listed below, + up to and including the entire Internet. + ATTACK_VECTOR_ADJACENT (2): + The vulnerable component is bound to the + network stack, but the attack is limited at the + protocol level to a logically adjacent topology. + ATTACK_VECTOR_LOCAL (3): + The vulnerable component is not bound to the + network stack and the attacker's path is via + read/write/execute capabilities. + ATTACK_VECTOR_PHYSICAL (4): + The attack requires the attacker to + physically touch or manipulate the vulnerable + component. + """ + ATTACK_VECTOR_UNSPECIFIED = 0 + ATTACK_VECTOR_NETWORK = 1 + ATTACK_VECTOR_ADJACENT = 2 + ATTACK_VECTOR_LOCAL = 3 + ATTACK_VECTOR_PHYSICAL = 4 + + class AttackComplexity(proto.Enum): + r"""This metric describes the conditions beyond the attacker's + control that must exist in order to exploit the vulnerability. + + Values: + ATTACK_COMPLEXITY_UNSPECIFIED (0): + Invalid value. + ATTACK_COMPLEXITY_LOW (1): + Specialized access conditions or extenuating + circumstances do not exist. An attacker can + expect repeatable success when attacking the + vulnerable component. + ATTACK_COMPLEXITY_HIGH (2): + A successful attack depends on conditions + beyond the attacker's control. That is, a + successful attack cannot be accomplished at + will, but requires the attacker to invest in + some measurable amount of effort in preparation + or execution against the vulnerable component + before a successful attack can be expected. + """ + ATTACK_COMPLEXITY_UNSPECIFIED = 0 + ATTACK_COMPLEXITY_LOW = 1 + ATTACK_COMPLEXITY_HIGH = 2 + + class PrivilegesRequired(proto.Enum): + r"""This metric describes the level of privileges an attacker + must possess before successfully exploiting the vulnerability. + + Values: + PRIVILEGES_REQUIRED_UNSPECIFIED (0): + Invalid value. + PRIVILEGES_REQUIRED_NONE (1): + The attacker is unauthorized prior to attack, + and therefore does not require any access to + settings or files of the vulnerable system to + carry out an attack. + PRIVILEGES_REQUIRED_LOW (2): + The attacker requires privileges that provide + basic user capabilities that could normally + affect only settings and files owned by a user. + Alternatively, an attacker with Low privileges + has the ability to access only non-sensitive + resources. + PRIVILEGES_REQUIRED_HIGH (3): + The attacker requires privileges that provide + significant (e.g., administrative) control over + the vulnerable component allowing access to + component-wide settings and files. + """ + PRIVILEGES_REQUIRED_UNSPECIFIED = 0 + PRIVILEGES_REQUIRED_NONE = 1 + PRIVILEGES_REQUIRED_LOW = 2 + PRIVILEGES_REQUIRED_HIGH = 3 + + class UserInteraction(proto.Enum): + r"""This metric captures the requirement for a human user, other + than the attacker, to participate in the successful compromise + of the vulnerable component. + + Values: + USER_INTERACTION_UNSPECIFIED (0): + Invalid value. + USER_INTERACTION_NONE (1): + The vulnerable system can be exploited + without interaction from any user. + USER_INTERACTION_REQUIRED (2): + Successful exploitation of this vulnerability + requires a user to take some action before the + vulnerability can be exploited. + """ + USER_INTERACTION_UNSPECIFIED = 0 + USER_INTERACTION_NONE = 1 + USER_INTERACTION_REQUIRED = 2 + + class Scope(proto.Enum): + r"""The Scope metric captures whether a vulnerability in one + vulnerable component impacts resources in components beyond its + security scope. + + Values: + SCOPE_UNSPECIFIED (0): + Invalid value. + SCOPE_UNCHANGED (1): + An exploited vulnerability can only affect + resources managed by the same security + authority. + SCOPE_CHANGED (2): + An exploited vulnerability can affect + resources beyond the security scope managed by + the security authority of the vulnerable + component. + """ + SCOPE_UNSPECIFIED = 0 + SCOPE_UNCHANGED = 1 + SCOPE_CHANGED = 2 + + class Impact(proto.Enum): + r"""The Impact metrics capture the effects of a successfully + exploited vulnerability on the component that suffers the worst + outcome that is most directly and predictably associated with + the attack. + + Values: + IMPACT_UNSPECIFIED (0): + Invalid value. + IMPACT_HIGH (1): + High impact. + IMPACT_LOW (2): + Low impact. + IMPACT_NONE (3): + No impact. + """ + IMPACT_UNSPECIFIED = 0 + IMPACT_HIGH = 1 + IMPACT_LOW = 2 + IMPACT_NONE = 3 + + base_score: float = proto.Field( + proto.DOUBLE, + number=1, + ) + attack_vector: AttackVector = proto.Field( + proto.ENUM, + number=2, + enum=AttackVector, + ) + attack_complexity: AttackComplexity = proto.Field( + proto.ENUM, + number=3, + enum=AttackComplexity, + ) + privileges_required: PrivilegesRequired = proto.Field( + proto.ENUM, + number=4, + enum=PrivilegesRequired, + ) + user_interaction: UserInteraction = proto.Field( + proto.ENUM, + number=5, + enum=UserInteraction, + ) + scope: Scope = proto.Field( + proto.ENUM, + number=6, + enum=Scope, + ) + confidentiality_impact: Impact = proto.Field( + proto.ENUM, + number=7, + enum=Impact, + ) + integrity_impact: Impact = proto.Field( + proto.ENUM, + number=8, + enum=Impact, + ) + availability_impact: Impact = proto.Field( + proto.ENUM, + number=9, + enum=Impact, + ) + + +class Package(proto.Message): + r"""Package is a generic definition of a package. + + Attributes: + package_name (str): + The name of the package where the + vulnerability was detected. + cpe_uri (str): + The CPE URI where the vulnerability was + detected. + package_type (str): + Type of package, for example, os, maven, or + go. + package_version (str): + The version of the package. + """ + + package_name: str = proto.Field( + proto.STRING, + number=1, + ) + cpe_uri: str = proto.Field( + proto.STRING, + number=2, + ) + package_type: str = proto.Field( + proto.STRING, + number=3, + ) + package_version: str = proto.Field( + proto.STRING, + number=4, + ) + + +class SecurityBulletin(proto.Message): + r"""SecurityBulletin are notifications of vulnerabilities of + Google products. + + Attributes: + bulletin_id (str): + ID of the bulletin corresponding to the + vulnerability. + submission_time (google.protobuf.timestamp_pb2.Timestamp): + Submission time of this Security Bulletin. + suggested_upgrade_version (str): + This represents a version that the cluster + receiving this notification should be upgraded + to, based on its current version. For example, + 1.15.0 + """ + + bulletin_id: str = proto.Field( + proto.STRING, + number=1, + ) + submission_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + suggested_upgrade_version: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py new file mode 100644 index 000000000000..09f81fcd1556 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 BatchCreateResourceValueConfigs +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_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 securitycenter_v2 + + +async def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + requests = securitycenter_v2.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = await client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py new file mode 100644 index 000000000000..c824e5cc44fc --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 BatchCreateResourceValueConfigs +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_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 securitycenter_v2 + + +def sample_batch_create_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + requests = securitycenter_v2.CreateResourceValueConfigRequest() + requests.parent = "parent_value" + requests.resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v2.BatchCreateResourceValueConfigsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_resource_value_configs(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_async.py new file mode 100644 index 000000000000..182589def6dd --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 BulkMuteFindings +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_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 securitycenter_v2 + + +async def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py new file mode 100644 index 000000000000..548a8582ba63 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 BulkMuteFindings +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_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 securitycenter_v2 + + +def sample_bulk_mute_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.BulkMuteFindingsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.bulk_mute_findings(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_async.py new file mode 100644 index 000000000000..fd21231017d3 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateBigQueryExport +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_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 securitycenter_v2 + + +async def sample_create_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = await client.create_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_sync.py new file mode 100644 index 000000000000..30002476f096 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_big_query_export_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateBigQueryExport +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_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 securitycenter_v2 + + +def sample_create_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateBigQueryExportRequest( + parent="parent_value", + big_query_export_id="big_query_export_id_value", + ) + + # Make the request + response = client.create_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_async.py new file mode 100644 index 000000000000..437f9ca84dee --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateFinding +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateFinding_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 securitycenter_v2 + + +async def sample_create_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = await client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateFinding_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_sync.py new file mode 100644 index 000000000000..175029b80519 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_finding_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateFinding +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateFinding_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 securitycenter_v2 + + +def sample_create_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateFindingRequest( + parent="parent_value", + finding_id="finding_id_value", + ) + + # Make the request + response = client.create_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateFinding_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py new file mode 100644 index 000000000000..274733b9f6cd --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateMuteConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_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 securitycenter_v2 + + +async def sample_create_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "STATIC" + + request = securitycenter_v2.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = await client.create_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py new file mode 100644 index 000000000000..bb135f66db0e --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_mute_config_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateMuteConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_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 securitycenter_v2 + + +def sample_create_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "STATIC" + + request = securitycenter_v2.CreateMuteConfigRequest( + parent="parent_value", + mute_config=mute_config, + mute_config_id="mute_config_id_value", + ) + + # Make the request + response = client.create_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_async.py new file mode 100644 index 000000000000..20e2140445ba --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateNotificationConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_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 securitycenter_v2 + + +async def sample_create_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = await client.create_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_sync.py new file mode 100644 index 000000000000..1d72841f51ef --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_notification_config_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateNotificationConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_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 securitycenter_v2 + + +def sample_create_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateNotificationConfigRequest( + parent="parent_value", + config_id="config_id_value", + ) + + # Make the request + response = client.create_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_async.py new file mode 100644 index 000000000000..0760b9e60b29 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateSource +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateSource_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 securitycenter_v2 + + +async def sample_create_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateSource_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_sync.py new file mode 100644 index 000000000000..b435396de991 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_create_source_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 CreateSource +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_CreateSource_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 securitycenter_v2 + + +def sample_create_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.CreateSourceRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_CreateSource_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_async.py new file mode 100644 index 000000000000..09514a6c586b --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteBigQueryExport +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_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 securitycenter_v2 + + +async def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + await client.delete_big_query_export(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_sync.py new file mode 100644 index 000000000000..b9c79943893a --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_big_query_export_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteBigQueryExport +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_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 securitycenter_v2 + + +def sample_delete_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteBigQueryExportRequest( + name="name_value", + ) + + # Make the request + client.delete_big_query_export(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_async.py new file mode 100644 index 000000000000..f0f7a717f4d7 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteMuteConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_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 securitycenter_v2 + + +async def sample_delete_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_mute_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_sync.py new file mode 100644 index 000000000000..ca000be4b95a --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_mute_config_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteMuteConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_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 securitycenter_v2 + + +def sample_delete_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteMuteConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_mute_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_async.py new file mode 100644 index 000000000000..d752dc809b16 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteNotificationConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_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 securitycenter_v2 + + +async def sample_delete_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_notification_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_sync.py new file mode 100644 index 000000000000..9b650404c527 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_notification_config_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteNotificationConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_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 securitycenter_v2 + + +def sample_delete_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteNotificationConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_notification_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_async.py new file mode 100644 index 000000000000..5063c4556cd2 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteResourceValueConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_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 securitycenter_v2 + + +async def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + await client.delete_resource_value_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py new file mode 100644 index 000000000000..eb65e65e197a --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 DeleteResourceValueConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_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 securitycenter_v2 + + +def sample_delete_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.DeleteResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + client.delete_resource_value_config(request=request) + + +# [END securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_async.py new file mode 100644 index 000000000000..1e2892d7847e --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetBigQueryExport +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_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 securitycenter_v2 + + +async def sample_get_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = await client.get_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_sync.py new file mode 100644 index 000000000000..b3b4388e1b5e --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_big_query_export_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetBigQueryExport +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_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 securitycenter_v2 + + +def sample_get_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetBigQueryExportRequest( + name="name_value", + ) + + # Make the request + response = client.get_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_async.py new file mode 100644 index 000000000000..e4328bd28868 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetIamPolicy_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 securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetIamPolicy_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_sync.py new file mode 100644 index 000000000000..63c5251ec9ad --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_iam_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetIamPolicy_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_async.py new file mode 100644 index 000000000000..12d09197fc9d --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetMuteConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetMuteConfig_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 securitycenter_v2 + + +async def sample_get_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetMuteConfig_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_sync.py new file mode 100644 index 000000000000..e1831aa59d7c --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_mute_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetMuteConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetMuteConfig_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 securitycenter_v2 + + +def sample_get_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetMuteConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetMuteConfig_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_async.py new file mode 100644 index 000000000000..ae049e4c68c3 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetNotificationConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_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 securitycenter_v2 + + +async def sample_get_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_sync.py new file mode 100644 index 000000000000..d40ad524a70d --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_notification_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetNotificationConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_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 securitycenter_v2 + + +def sample_get_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetNotificationConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_async.py new file mode 100644 index 000000000000..935654ee8a31 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetResourceValueConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_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 securitycenter_v2 + + +async def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_sync.py new file mode 100644 index 000000000000..a6934cd25773 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_resource_value_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetResourceValueConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_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 securitycenter_v2 + + +def sample_get_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetResourceValueConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_async.py new file mode 100644 index 000000000000..d684db849aeb --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetSimulation +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetSimulation_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 securitycenter_v2 + + +async def sample_get_simulation(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_simulation(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetSimulation_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_sync.py new file mode 100644 index 000000000000..d018f7f13666 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_simulation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetSimulation +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetSimulation_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 securitycenter_v2 + + +def sample_get_simulation(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSimulationRequest( + name="name_value", + ) + + # Make the request + response = client.get_simulation(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetSimulation_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_async.py new file mode 100644 index 000000000000..19aa30222c97 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetSource +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetSource_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 securitycenter_v2 + + +async def sample_get_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetSource_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_sync.py new file mode 100644 index 000000000000..c4dcb283be53 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_source_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetSource +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetSource_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 securitycenter_v2 + + +def sample_get_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetSourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetSource_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_async.py new file mode 100644 index 000000000000..6d72482fad60 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetValuedResource +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetValuedResource_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 securitycenter_v2 + + +async def sample_get_valued_resource(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_valued_resource(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetValuedResource_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_sync.py new file mode 100644 index 000000000000..28badb6a1218 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_get_valued_resource_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GetValuedResource +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GetValuedResource_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 securitycenter_v2 + + +def sample_get_valued_resource(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GetValuedResourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_valued_resource(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GetValuedResource_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_async.py new file mode 100644 index 000000000000..35741f769568 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GroupFindings +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GroupFindings_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 securitycenter_v2 + + +async def sample_group_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GroupFindings_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_sync.py new file mode 100644 index 000000000000..a9968aade568 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_group_findings_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 GroupFindings +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_GroupFindings_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 securitycenter_v2 + + +def sample_group_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.GroupFindingsRequest( + parent="parent_value", + group_by="group_by_value", + ) + + # Make the request + page_result = client.group_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_GroupFindings_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_async.py new file mode 100644 index 000000000000..0de8471f9b74 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListAttackPaths +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListAttackPaths_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 securitycenter_v2 + + +async def sample_list_attack_paths(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListAttackPaths_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_sync.py new file mode 100644 index 000000000000..27cd22123449 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_attack_paths_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListAttackPaths +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListAttackPaths_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 securitycenter_v2 + + +def sample_list_attack_paths(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListAttackPathsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_attack_paths(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListAttackPaths_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_async.py new file mode 100644 index 000000000000..e47b6e0585de --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListBigQueryExports +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_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 securitycenter_v2 + + +async def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_sync.py new file mode 100644 index 000000000000..a2ab227b5ca0 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_big_query_exports_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListBigQueryExports +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_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 securitycenter_v2 + + +def sample_list_big_query_exports(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListBigQueryExportsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_big_query_exports(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_async.py new file mode 100644 index 000000000000..6c288226cad1 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListFindings +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListFindings_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 securitycenter_v2 + + +async def sample_list_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListFindings_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_sync.py new file mode 100644 index 000000000000..8aa84c3d1450 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_findings_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListFindings +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListFindings_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 securitycenter_v2 + + +def sample_list_findings(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListFindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListFindings_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_async.py new file mode 100644 index 000000000000..b374f7cace05 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListMuteConfigs +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_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 securitycenter_v2 + + +async def sample_list_mute_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_sync.py new file mode 100644 index 000000000000..9910452c0653 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_mute_configs_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListMuteConfigs +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_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 securitycenter_v2 + + +def sample_list_mute_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListMuteConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_mute_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_async.py new file mode 100644 index 000000000000..c42f84b0e5c2 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListNotificationConfigs +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_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 securitycenter_v2 + + +async def sample_list_notification_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_sync.py new file mode 100644 index 000000000000..749ac4c226df --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_notification_configs_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListNotificationConfigs +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_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 securitycenter_v2 + + +def sample_list_notification_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListNotificationConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_notification_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_async.py new file mode 100644 index 000000000000..7ea7d3cb138c --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListResourceValueConfigs +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_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 securitycenter_v2 + + +async def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py new file mode 100644 index 000000000000..de3aa53fcf7f --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListResourceValueConfigs +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_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 securitycenter_v2 + + +def sample_list_resource_value_configs(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListResourceValueConfigsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_value_configs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_async.py new file mode 100644 index 000000000000..e8e9b525586c --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListSources +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListSources_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 securitycenter_v2 + + +async def sample_list_sources(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListSources_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_sync.py new file mode 100644 index 000000000000..1941d1558472 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_sources_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListSources +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListSources_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 securitycenter_v2 + + +def sample_list_sources(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListSourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListSources_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_async.py new file mode 100644 index 000000000000..88ae351bcda8 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListValuedResources +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListValuedResources_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 securitycenter_v2 + + +async def sample_list_valued_resources(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListValuedResources_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_sync.py new file mode 100644 index 000000000000..35b90be4a15b --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_list_valued_resources_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 ListValuedResources +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_ListValuedResources_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 securitycenter_v2 + + +def sample_list_valued_resources(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.ListValuedResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_valued_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_ListValuedResources_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_async.py new file mode 100644 index 000000000000..f83c03070ebf --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 SetFindingState +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetFindingState_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 securitycenter_v2 + + +async def sample_set_finding_state(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = await client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetFindingState_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_sync.py new file mode 100644 index 000000000000..45f8a0a539a2 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_finding_state_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 SetFindingState +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetFindingState_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 securitycenter_v2 + + +def sample_set_finding_state(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetFindingStateRequest( + name="name_value", + state="INACTIVE", + ) + + # Make the request + response = client.set_finding_state(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetFindingState_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_async.py new file mode 100644 index 000000000000..2c16ac80c521 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetIamPolicy_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 securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetIamPolicy_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_sync.py new file mode 100644 index 000000000000..460629d25c3a --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_iam_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetIamPolicy_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_async.py new file mode 100644 index 000000000000..1e4c52470ed2 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 SetMute +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetMute_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 securitycenter_v2 + + +async def sample_set_mute(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = await client.set_mute(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetMute_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_sync.py new file mode 100644 index 000000000000..047c41733d0a --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_set_mute_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 SetMute +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_SetMute_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 securitycenter_v2 + + +def sample_set_mute(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.SetMuteRequest( + name="name_value", + mute="UNDEFINED", + ) + + # Make the request + response = client.set_mute(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_SetMute_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_async.py new file mode 100644 index 000000000000..bd5d0532ee4d --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_TestIamPermissions_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 securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_TestIamPermissions_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_sync.py new file mode 100644 index 000000000000..0be3fd09b0c8 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_test_iam_permissions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import securitycenter_v2 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_TestIamPermissions_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_async.py new file mode 100644 index 000000000000..b8f63f0b812a --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateBigQueryExport +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_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 securitycenter_v2 + + +async def sample_update_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateBigQueryExportRequest( + ) + + # Make the request + response = await client.update_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_sync.py new file mode 100644 index 000000000000..0c101eac0e1b --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_big_query_export_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateBigQueryExport +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_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 securitycenter_v2 + + +def sample_update_big_query_export(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateBigQueryExportRequest( + ) + + # Make the request + response = client.update_big_query_export(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_async.py new file mode 100644 index 000000000000..2c89ce1d1032 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateExternalSystem +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_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 securitycenter_v2 + + +async def sample_update_external_system(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateExternalSystemRequest( + ) + + # Make the request + response = await client.update_external_system(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_sync.py new file mode 100644 index 000000000000..a1f26954c850 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_external_system_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateExternalSystem +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_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 securitycenter_v2 + + +def sample_update_external_system(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateExternalSystemRequest( + ) + + # Make the request + response = client.update_external_system(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_async.py new file mode 100644 index 000000000000..fb650c701471 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateFinding +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateFinding_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 securitycenter_v2 + + +async def sample_update_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateFindingRequest( + ) + + # Make the request + response = await client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateFinding_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_sync.py new file mode 100644 index 000000000000..836dcf9c07a9 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_finding_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateFinding +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateFinding_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 securitycenter_v2 + + +def sample_update_finding(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateFindingRequest( + ) + + # Make the request + response = client.update_finding(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateFinding_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py new file mode 100644 index 000000000000..eaad23353dd6 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateMuteConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_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 securitycenter_v2 + + +async def sample_update_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "STATIC" + + request = securitycenter_v2.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = await client.update_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py new file mode 100644 index 000000000000..b7caba9cce40 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_mute_config_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateMuteConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_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 securitycenter_v2 + + +def sample_update_mute_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + mute_config = securitycenter_v2.MuteConfig() + mute_config.filter = "filter_value" + mute_config.type_ = "STATIC" + + request = securitycenter_v2.UpdateMuteConfigRequest( + mute_config=mute_config, + ) + + # Make the request + response = client.update_mute_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_async.py new file mode 100644 index 000000000000..168abc290e11 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateNotificationConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_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 securitycenter_v2 + + +async def sample_update_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateNotificationConfigRequest( + ) + + # Make the request + response = await client.update_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_sync.py new file mode 100644 index 000000000000..3643aaf5c813 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_notification_config_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateNotificationConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_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 securitycenter_v2 + + +def sample_update_notification_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateNotificationConfigRequest( + ) + + # Make the request + response = client.update_notification_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py new file mode 100644 index 000000000000..e8badabb634c --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateResourceValueConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_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 securitycenter_v2 + + +async def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + resource_value_config = securitycenter_v2.ResourceValueConfig() + resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v2.UpdateResourceValueConfigRequest( + resource_value_config=resource_value_config, + ) + + # Make the request + response = await client.update_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py new file mode 100644 index 000000000000..748d9b291a25 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_resource_value_config_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateResourceValueConfig +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_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 securitycenter_v2 + + +def sample_update_resource_value_config(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + resource_value_config = securitycenter_v2.ResourceValueConfig() + resource_value_config.tag_values = ['tag_values_value1', 'tag_values_value2'] + + request = securitycenter_v2.UpdateResourceValueConfigRequest( + resource_value_config=resource_value_config, + ) + + # Make the request + response = client.update_resource_value_config(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_async.py new file mode 100644 index 000000000000..44663258c63d --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateSecurityMarks +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_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 securitycenter_v2 + + +async def sample_update_security_marks(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSecurityMarksRequest( + ) + + # Make the request + response = await client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_sync.py new file mode 100644 index 000000000000..6f30a6a41442 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_security_marks_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateSecurityMarks +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_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 securitycenter_v2 + + +def sample_update_security_marks(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSecurityMarksRequest( + ) + + # Make the request + response = client.update_security_marks(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_async.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_async.py new file mode 100644 index 000000000000..200906386274 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateSource +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateSource_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 securitycenter_v2 + + +async def sample_update_source(): + # Create a client + client = securitycenter_v2.SecurityCenterAsyncClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSourceRequest( + ) + + # Make the request + response = await client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateSource_async] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_sync.py b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_sync.py new file mode 100644 index 000000000000..c1299083aaf6 --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/securitycenter_v2_generated_security_center_update_source_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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 UpdateSource +# 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-securitycenter + + +# [START securitycenter_v2_generated_SecurityCenter_UpdateSource_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 securitycenter_v2 + + +def sample_update_source(): + # Create a client + client = securitycenter_v2.SecurityCenterClient() + + # Initialize request argument(s) + request = securitycenter_v2.UpdateSourceRequest( + ) + + # Make the request + response = client.update_source(request=request) + + # Handle the response + print(response) + +# [END securitycenter_v2_generated_SecurityCenter_UpdateSource_sync] diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json b/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json index ec515b030621..29c4a8e18158 100644 --- a/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json +++ b/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-securitycenter", - "version": "1.27.0" + "version": "1.28.0" }, "snippets": [ { diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json b/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json index 9d94361df18e..a73fa0244910 100644 --- a/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json +++ b/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-securitycenter", - "version": "1.27.0" + "version": "1.28.0" }, "snippets": [ { diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json b/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json index 490db3155719..85e69947eb4a 100644 --- a/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json +++ b/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-securitycenter", - "version": "1.27.0" + "version": "1.28.0" }, "snippets": [ { diff --git a/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json b/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json new file mode 100644 index 000000000000..6672c033126b --- /dev/null +++ b/packages/google-cloud-securitycenter/samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json @@ -0,0 +1,6607 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.securitycenter.v2", + "version": "v2" + } + ], + "language": "PYTHON", + "name": "google-cloud-securitycenter", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.batch_create_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BatchCreateResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BatchCreateResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "requests", + "type": "MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse", + "shortName": "batch_create_resource_value_configs" + }, + "description": "Sample for BatchCreateResourceValueConfigs", + "file": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.batch_create_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BatchCreateResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BatchCreateResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "requests", + "type": "MutableSequence[google.cloud.securitycenter_v2.types.CreateResourceValueConfigRequest]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.BatchCreateResourceValueConfigsResponse", + "shortName": "batch_create_resource_value_configs" + }, + "description": "Sample for BatchCreateResourceValueConfigs", + "file": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_BatchCreateResourceValueConfigs_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": "securitycenter_v2_generated_security_center_batch_create_resource_value_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.bulk_mute_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BulkMuteFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BulkMuteFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest" + }, + { + "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.api_core.operation_async.AsyncOperation", + "shortName": "bulk_mute_findings" + }, + "description": "Sample for BulkMuteFindings", + "file": "securitycenter_v2_generated_security_center_bulk_mute_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v2_generated_security_center_bulk_mute_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.bulk_mute_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.BulkMuteFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "BulkMuteFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.BulkMuteFindingsRequest" + }, + { + "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.api_core.operation.Operation", + "shortName": "bulk_mute_findings" + }, + "description": "Sample for BulkMuteFindings", + "file": "securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_BulkMuteFindings_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": "securitycenter_v2_generated_security_center_bulk_mute_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v2.types.BigQueryExport" + }, + { + "name": "big_query_export_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.securitycenter_v2.types.BigQueryExport", + "shortName": "create_big_query_export" + }, + "description": "Sample for CreateBigQueryExport", + "file": "securitycenter_v2_generated_security_center_create_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v2_generated_security_center_create_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateBigQueryExportRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v2.types.BigQueryExport" + }, + { + "name": "big_query_export_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.securitycenter_v2.types.BigQueryExport", + "shortName": "create_big_query_export" + }, + "description": "Sample for CreateBigQueryExport", + "file": "securitycenter_v2_generated_security_center_create_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateBigQueryExport_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": "securitycenter_v2_generated_security_center_create_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v2.types.Finding" + }, + { + "name": "finding_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.securitycenter_v2.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v2_generated_security_center_create_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateFinding_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": "securitycenter_v2_generated_security_center_create_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_finding", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateFindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v2.types.Finding" + }, + { + "name": "finding_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.securitycenter_v2.types.Finding", + "shortName": "create_finding" + }, + "description": "Sample for CreateFinding", + "file": "securitycenter_v2_generated_security_center_create_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateFinding_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": "securitycenter_v2_generated_security_center_create_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateMuteConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v2.types.MuteConfig" + }, + { + "name": "mute_config_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.securitycenter_v2.types.MuteConfig", + "shortName": "create_mute_config" + }, + "description": "Sample for CreateMuteConfig", + "file": "securitycenter_v2_generated_security_center_create_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_create_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateMuteConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v2.types.MuteConfig" + }, + { + "name": "mute_config_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.securitycenter_v2.types.MuteConfig", + "shortName": "create_mute_config" + }, + "description": "Sample for CreateMuteConfig", + "file": "securitycenter_v2_generated_security_center_create_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateMuteConfig_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_create_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v2.types.NotificationConfig" + }, + { + "name": "config_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.securitycenter_v2.types.NotificationConfig", + "shortName": "create_notification_config" + }, + "description": "Sample for CreateNotificationConfig", + "file": "securitycenter_v2_generated_security_center_create_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v2_generated_security_center_create_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateNotificationConfigRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v2.types.NotificationConfig" + }, + { + "name": "config_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.securitycenter_v2.types.NotificationConfig", + "shortName": "create_notification_config" + }, + "description": "Sample for CreateNotificationConfig", + "file": "securitycenter_v2_generated_security_center_create_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateNotificationConfig_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": "securitycenter_v2_generated_security_center_create_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v2.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v2_generated_security_center_create_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateSource_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": "securitycenter_v2_generated_security_center_create_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.create_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.CreateSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "CreateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.CreateSourceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v2.types.Source" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Source", + "shortName": "create_source" + }, + "description": "Sample for CreateSource", + "file": "securitycenter_v2_generated_security_center_create_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_CreateSource_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": "securitycenter_v2_generated_security_center_create_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest" + }, + { + "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_big_query_export" + }, + "description": "Sample for DeleteBigQueryExport", + "file": "securitycenter_v2_generated_security_center_delete_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_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": "securitycenter_v2_generated_security_center_delete_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteBigQueryExportRequest" + }, + { + "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_big_query_export" + }, + "description": "Sample for DeleteBigQueryExport", + "file": "securitycenter_v2_generated_security_center_delete_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteBigQueryExport_sync", + "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": "securitycenter_v2_generated_security_center_delete_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest" + }, + { + "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_mute_config" + }, + "description": "Sample for DeleteMuteConfig", + "file": "securitycenter_v2_generated_security_center_delete_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_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": "securitycenter_v2_generated_security_center_delete_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteMuteConfigRequest" + }, + { + "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_mute_config" + }, + "description": "Sample for DeleteMuteConfig", + "file": "securitycenter_v2_generated_security_center_delete_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteMuteConfig_sync", + "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": "securitycenter_v2_generated_security_center_delete_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest" + }, + { + "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_notification_config" + }, + "description": "Sample for DeleteNotificationConfig", + "file": "securitycenter_v2_generated_security_center_delete_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_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": "securitycenter_v2_generated_security_center_delete_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteNotificationConfigRequest" + }, + { + "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_notification_config" + }, + "description": "Sample for DeleteNotificationConfig", + "file": "securitycenter_v2_generated_security_center_delete_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteNotificationConfig_sync", + "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": "securitycenter_v2_generated_security_center_delete_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.delete_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest" + }, + { + "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_resource_value_config" + }, + "description": "Sample for DeleteResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_delete_resource_value_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_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": "securitycenter_v2_generated_security_center_delete_resource_value_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.delete_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.DeleteResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "DeleteResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.DeleteResourceValueConfigRequest" + }, + { + "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_resource_value_config" + }, + "description": "Sample for DeleteResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_DeleteResourceValueConfig_sync", + "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": "securitycenter_v2_generated_security_center_delete_resource_value_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetBigQueryExportRequest" + }, + { + "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.securitycenter_v2.types.BigQueryExport", + "shortName": "get_big_query_export" + }, + "description": "Sample for GetBigQueryExport", + "file": "securitycenter_v2_generated_security_center_get_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_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": "securitycenter_v2_generated_security_center_get_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetBigQueryExportRequest" + }, + { + "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.securitycenter_v2.types.BigQueryExport", + "shortName": "get_big_query_export" + }, + "description": "Sample for GetBigQueryExport", + "file": "securitycenter_v2_generated_security_center_get_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetBigQueryExport_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": "securitycenter_v2_generated_security_center_get_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v2_generated_security_center_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "securitycenter_v2_generated_security_center_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetMuteConfigRequest" + }, + { + "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.securitycenter_v2.types.MuteConfig", + "shortName": "get_mute_config" + }, + "description": "Sample for GetMuteConfig", + "file": "securitycenter_v2_generated_security_center_get_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetMuteConfig_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": "securitycenter_v2_generated_security_center_get_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetMuteConfigRequest" + }, + { + "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.securitycenter_v2.types.MuteConfig", + "shortName": "get_mute_config" + }, + "description": "Sample for GetMuteConfig", + "file": "securitycenter_v2_generated_security_center_get_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetMuteConfig_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": "securitycenter_v2_generated_security_center_get_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetNotificationConfigRequest" + }, + { + "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.securitycenter_v2.types.NotificationConfig", + "shortName": "get_notification_config" + }, + "description": "Sample for GetNotificationConfig", + "file": "securitycenter_v2_generated_security_center_get_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_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": "securitycenter_v2_generated_security_center_get_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetNotificationConfigRequest" + }, + { + "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.securitycenter_v2.types.NotificationConfig", + "shortName": "get_notification_config" + }, + "description": "Sample for GetNotificationConfig", + "file": "securitycenter_v2_generated_security_center_get_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetNotificationConfig_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": "securitycenter_v2_generated_security_center_get_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest" + }, + { + "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.securitycenter_v2.types.ResourceValueConfig", + "shortName": "get_resource_value_config" + }, + "description": "Sample for GetResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_get_resource_value_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_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": "securitycenter_v2_generated_security_center_get_resource_value_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetResourceValueConfigRequest" + }, + { + "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.securitycenter_v2.types.ResourceValueConfig", + "shortName": "get_resource_value_config" + }, + "description": "Sample for GetResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_get_resource_value_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetResourceValueConfig_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": "securitycenter_v2_generated_security_center_get_resource_value_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_simulation", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSimulation", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSimulation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetSimulationRequest" + }, + { + "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.securitycenter_v2.types.Simulation", + "shortName": "get_simulation" + }, + "description": "Sample for GetSimulation", + "file": "securitycenter_v2_generated_security_center_get_simulation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSimulation_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": "securitycenter_v2_generated_security_center_get_simulation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_simulation", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSimulation", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSimulation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetSimulationRequest" + }, + { + "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.securitycenter_v2.types.Simulation", + "shortName": "get_simulation" + }, + "description": "Sample for GetSimulation", + "file": "securitycenter_v2_generated_security_center_get_simulation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSimulation_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": "securitycenter_v2_generated_security_center_get_simulation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetSourceRequest" + }, + { + "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.securitycenter_v2.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v2_generated_security_center_get_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSource_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": "securitycenter_v2_generated_security_center_get_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetSourceRequest" + }, + { + "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.securitycenter_v2.types.Source", + "shortName": "get_source" + }, + "description": "Sample for GetSource", + "file": "securitycenter_v2_generated_security_center_get_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetSource_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": "securitycenter_v2_generated_security_center_get_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.get_valued_resource", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetValuedResource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetValuedResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetValuedResourceRequest" + }, + { + "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.securitycenter_v2.types.ValuedResource", + "shortName": "get_valued_resource" + }, + "description": "Sample for GetValuedResource", + "file": "securitycenter_v2_generated_security_center_get_valued_resource_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetValuedResource_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": "securitycenter_v2_generated_security_center_get_valued_resource_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.get_valued_resource", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GetValuedResource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GetValuedResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GetValuedResourceRequest" + }, + { + "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.securitycenter_v2.types.ValuedResource", + "shortName": "get_valued_resource" + }, + "description": "Sample for GetValuedResource", + "file": "securitycenter_v2_generated_security_center_get_valued_resource_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GetValuedResource_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": "securitycenter_v2_generated_security_center_get_valued_resource_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsAsyncPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v2_generated_security_center_group_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GroupFindings_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_group_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.group_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.GroupFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "GroupFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.GroupFindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "group_by", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.services.security_center.pagers.GroupFindingsPager", + "shortName": "group_findings" + }, + "description": "Sample for GroupFindings", + "file": "securitycenter_v2_generated_security_center_group_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_GroupFindings_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_group_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_attack_paths", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListAttackPaths", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAttackPaths" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListAttackPathsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListAttackPathsAsyncPager", + "shortName": "list_attack_paths" + }, + "description": "Sample for ListAttackPaths", + "file": "securitycenter_v2_generated_security_center_list_attack_paths_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v2_generated_security_center_list_attack_paths_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_attack_paths", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListAttackPaths", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListAttackPaths" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListAttackPathsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListAttackPathsPager", + "shortName": "list_attack_paths" + }, + "description": "Sample for ListAttackPaths", + "file": "securitycenter_v2_generated_security_center_list_attack_paths_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListAttackPaths_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": "securitycenter_v2_generated_security_center_list_attack_paths_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_big_query_exports", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListBigQueryExports", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListBigQueryExports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsAsyncPager", + "shortName": "list_big_query_exports" + }, + "description": "Sample for ListBigQueryExports", + "file": "securitycenter_v2_generated_security_center_list_big_query_exports_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v2_generated_security_center_list_big_query_exports_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_big_query_exports", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListBigQueryExports", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListBigQueryExports" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListBigQueryExportsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListBigQueryExportsPager", + "shortName": "list_big_query_exports" + }, + "description": "Sample for ListBigQueryExports", + "file": "securitycenter_v2_generated_security_center_list_big_query_exports_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListBigQueryExports_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": "securitycenter_v2_generated_security_center_list_big_query_exports_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListFindingsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListFindingsAsyncPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v2_generated_security_center_list_findings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListFindings_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": "securitycenter_v2_generated_security_center_list_findings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_findings", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListFindings", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListFindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListFindingsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListFindingsPager", + "shortName": "list_findings" + }, + "description": "Sample for ListFindings", + "file": "securitycenter_v2_generated_security_center_list_findings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListFindings_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": "securitycenter_v2_generated_security_center_list_findings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_mute_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListMuteConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListMuteConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListMuteConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsAsyncPager", + "shortName": "list_mute_configs" + }, + "description": "Sample for ListMuteConfigs", + "file": "securitycenter_v2_generated_security_center_list_mute_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v2_generated_security_center_list_mute_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_mute_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListMuteConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListMuteConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListMuteConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListMuteConfigsPager", + "shortName": "list_mute_configs" + }, + "description": "Sample for ListMuteConfigs", + "file": "securitycenter_v2_generated_security_center_list_mute_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListMuteConfigs_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": "securitycenter_v2_generated_security_center_list_mute_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_notification_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListNotificationConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListNotificationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsAsyncPager", + "shortName": "list_notification_configs" + }, + "description": "Sample for ListNotificationConfigs", + "file": "securitycenter_v2_generated_security_center_list_notification_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v2_generated_security_center_list_notification_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_notification_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListNotificationConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListNotificationConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListNotificationConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListNotificationConfigsPager", + "shortName": "list_notification_configs" + }, + "description": "Sample for ListNotificationConfigs", + "file": "securitycenter_v2_generated_security_center_list_notification_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListNotificationConfigs_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": "securitycenter_v2_generated_security_center_list_notification_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsAsyncPager", + "shortName": "list_resource_value_configs" + }, + "description": "Sample for ListResourceValueConfigs", + "file": "securitycenter_v2_generated_security_center_list_resource_value_configs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v2_generated_security_center_list_resource_value_configs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_resource_value_configs", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListResourceValueConfigs", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListResourceValueConfigs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListResourceValueConfigsRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListResourceValueConfigsPager", + "shortName": "list_resource_value_configs" + }, + "description": "Sample for ListResourceValueConfigs", + "file": "securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListResourceValueConfigs_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": "securitycenter_v2_generated_security_center_list_resource_value_configs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListSourcesRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListSourcesAsyncPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v2_generated_security_center_list_sources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListSources_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": "securitycenter_v2_generated_security_center_list_sources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_sources", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListSources", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListSources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListSourcesRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListSourcesPager", + "shortName": "list_sources" + }, + "description": "Sample for ListSources", + "file": "securitycenter_v2_generated_security_center_list_sources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListSources_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": "securitycenter_v2_generated_security_center_list_sources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.list_valued_resources", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListValuedResources", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListValuedResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListValuedResourcesRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesAsyncPager", + "shortName": "list_valued_resources" + }, + "description": "Sample for ListValuedResources", + "file": "securitycenter_v2_generated_security_center_list_valued_resources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v2_generated_security_center_list_valued_resources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.list_valued_resources", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.ListValuedResources", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "ListValuedResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.ListValuedResourcesRequest" + }, + { + "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.securitycenter_v2.services.security_center.pagers.ListValuedResourcesPager", + "shortName": "list_valued_resources" + }, + "description": "Sample for ListValuedResources", + "file": "securitycenter_v2_generated_security_center_list_valued_resources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_ListValuedResources_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": "securitycenter_v2_generated_security_center_list_valued_resources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v2.types.Finding.State" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v2_generated_security_center_set_finding_state_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetFindingState_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": "securitycenter_v2_generated_security_center_set_finding_state_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.set_finding_state", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetFindingState", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetFindingState" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.SetFindingStateRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "state", + "type": "google.cloud.securitycenter_v2.types.Finding.State" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Finding", + "shortName": "set_finding_state" + }, + "description": "Sample for SetFindingState", + "file": "securitycenter_v2_generated_security_center_set_finding_state_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetFindingState_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": "securitycenter_v2_generated_security_center_set_finding_state_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v2_generated_security_center_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.set_iam_policy", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetIamPolicy", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "securitycenter_v2_generated_security_center_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.set_mute", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetMute", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetMute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.SetMuteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "mute", + "type": "google.cloud.securitycenter_v2.types.Finding.Mute" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Finding", + "shortName": "set_mute" + }, + "description": "Sample for SetMute", + "file": "securitycenter_v2_generated_security_center_set_mute_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetMute_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": "securitycenter_v2_generated_security_center_set_mute_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.set_mute", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.SetMute", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "SetMute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.SetMuteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "mute", + "type": "google.cloud.securitycenter_v2.types.Finding.Mute" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.securitycenter_v2.types.Finding", + "shortName": "set_mute" + }, + "description": "Sample for SetMute", + "file": "securitycenter_v2_generated_security_center_set_mute_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_SetMute_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": "securitycenter_v2_generated_security_center_set_mute_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v2_generated_security_center_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_TestIamPermissions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.TestIamPermissions", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "securitycenter_v2_generated_security_center_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v2.types.BigQueryExport" + }, + { + "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.cloud.securitycenter_v2.types.BigQueryExport", + "shortName": "update_big_query_export" + }, + "description": "Sample for UpdateBigQueryExport", + "file": "securitycenter_v2_generated_security_center_update_big_query_export_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_update_big_query_export_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_big_query_export", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateBigQueryExport", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateBigQueryExport" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateBigQueryExportRequest" + }, + { + "name": "big_query_export", + "type": "google.cloud.securitycenter_v2.types.BigQueryExport" + }, + { + "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.cloud.securitycenter_v2.types.BigQueryExport", + "shortName": "update_big_query_export" + }, + "description": "Sample for UpdateBigQueryExport", + "file": "securitycenter_v2_generated_security_center_update_big_query_export_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateBigQueryExport_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_update_big_query_export_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_external_system", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateExternalSystem", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateExternalSystem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest" + }, + { + "name": "external_system", + "type": "google.cloud.securitycenter_v2.types.ExternalSystem" + }, + { + "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.cloud.securitycenter_v2.types.ExternalSystem", + "shortName": "update_external_system" + }, + "description": "Sample for UpdateExternalSystem", + "file": "securitycenter_v2_generated_security_center_update_external_system_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_update_external_system_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_external_system", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateExternalSystem", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateExternalSystem" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateExternalSystemRequest" + }, + { + "name": "external_system", + "type": "google.cloud.securitycenter_v2.types.ExternalSystem" + }, + { + "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.cloud.securitycenter_v2.types.ExternalSystem", + "shortName": "update_external_system" + }, + "description": "Sample for UpdateExternalSystem", + "file": "securitycenter_v2_generated_security_center_update_external_system_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateExternalSystem_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_update_external_system_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v2.types.Finding" + }, + { + "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.cloud.securitycenter_v2.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v2_generated_security_center_update_finding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateFinding_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_update_finding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_finding", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateFinding", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateFinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateFindingRequest" + }, + { + "name": "finding", + "type": "google.cloud.securitycenter_v2.types.Finding" + }, + { + "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.cloud.securitycenter_v2.types.Finding", + "shortName": "update_finding" + }, + "description": "Sample for UpdateFinding", + "file": "securitycenter_v2_generated_security_center_update_finding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateFinding_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_update_finding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v2.types.MuteConfig" + }, + { + "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.cloud.securitycenter_v2.types.MuteConfig", + "shortName": "update_mute_config" + }, + "description": "Sample for UpdateMuteConfig", + "file": "securitycenter_v2_generated_security_center_update_mute_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_update_mute_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_mute_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateMuteConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateMuteConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateMuteConfigRequest" + }, + { + "name": "mute_config", + "type": "google.cloud.securitycenter_v2.types.MuteConfig" + }, + { + "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.cloud.securitycenter_v2.types.MuteConfig", + "shortName": "update_mute_config" + }, + "description": "Sample for UpdateMuteConfig", + "file": "securitycenter_v2_generated_security_center_update_mute_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateMuteConfig_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_update_mute_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v2.types.NotificationConfig" + }, + { + "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.cloud.securitycenter_v2.types.NotificationConfig", + "shortName": "update_notification_config" + }, + "description": "Sample for UpdateNotificationConfig", + "file": "securitycenter_v2_generated_security_center_update_notification_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_update_notification_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_notification_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateNotificationConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateNotificationConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateNotificationConfigRequest" + }, + { + "name": "notification_config", + "type": "google.cloud.securitycenter_v2.types.NotificationConfig" + }, + { + "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.cloud.securitycenter_v2.types.NotificationConfig", + "shortName": "update_notification_config" + }, + "description": "Sample for UpdateNotificationConfig", + "file": "securitycenter_v2_generated_security_center_update_notification_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateNotificationConfig_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_update_notification_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest" + }, + { + "name": "resource_value_config", + "type": "google.cloud.securitycenter_v2.types.ResourceValueConfig" + }, + { + "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.cloud.securitycenter_v2.types.ResourceValueConfig", + "shortName": "update_resource_value_config" + }, + "description": "Sample for UpdateResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_update_resource_value_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_update_resource_value_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_resource_value_config", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateResourceValueConfig", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateResourceValueConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateResourceValueConfigRequest" + }, + { + "name": "resource_value_config", + "type": "google.cloud.securitycenter_v2.types.ResourceValueConfig" + }, + { + "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.cloud.securitycenter_v2.types.ResourceValueConfig", + "shortName": "update_resource_value_config" + }, + "description": "Sample for UpdateResourceValueConfig", + "file": "securitycenter_v2_generated_security_center_update_resource_value_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateResourceValueConfig_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_update_resource_value_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v2.types.SecurityMarks" + }, + { + "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.cloud.securitycenter_v2.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v2_generated_security_center_update_security_marks_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_update_security_marks_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_security_marks", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSecurityMarks", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSecurityMarks" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateSecurityMarksRequest" + }, + { + "name": "security_marks", + "type": "google.cloud.securitycenter_v2.types.SecurityMarks" + }, + { + "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.cloud.securitycenter_v2.types.SecurityMarks", + "shortName": "update_security_marks" + }, + "description": "Sample for UpdateSecurityMarks", + "file": "securitycenter_v2_generated_security_center_update_security_marks_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSecurityMarks_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_update_security_marks_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient", + "shortName": "SecurityCenterAsyncClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterAsyncClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v2.types.Source" + }, + { + "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.cloud.securitycenter_v2.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v2_generated_security_center_update_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSource_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_update_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient", + "shortName": "SecurityCenterClient" + }, + "fullName": "google.cloud.securitycenter_v2.SecurityCenterClient.update_source", + "method": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter.UpdateSource", + "service": { + "fullName": "google.cloud.securitycenter.v2.SecurityCenter", + "shortName": "SecurityCenter" + }, + "shortName": "UpdateSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.securitycenter_v2.types.UpdateSourceRequest" + }, + { + "name": "source", + "type": "google.cloud.securitycenter_v2.types.Source" + }, + { + "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.cloud.securitycenter_v2.types.Source", + "shortName": "update_source" + }, + "description": "Sample for UpdateSource", + "file": "securitycenter_v2_generated_security_center_update_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "securitycenter_v2_generated_SecurityCenter_UpdateSource_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "securitycenter_v2_generated_security_center_update_source_sync.py" + } + ] +} diff --git a/packages/google-cloud-securitycenter/scripts/fixup_securitycenter_v2_keywords.py b/packages/google-cloud-securitycenter/scripts/fixup_securitycenter_v2_keywords.py new file mode 100644 index 000000000000..9fab77ce6ce8 --- /dev/null +++ b/packages/google-cloud-securitycenter/scripts/fixup_securitycenter_v2_keywords.py @@ -0,0 +1,215 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class securitycenterCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_create_resource_value_configs': ('parent', 'requests', ), + 'bulk_mute_findings': ('parent', 'filter', ), + 'create_big_query_export': ('parent', 'big_query_export', 'big_query_export_id', ), + 'create_finding': ('parent', 'finding_id', 'finding', ), + 'create_mute_config': ('parent', 'mute_config', 'mute_config_id', ), + 'create_notification_config': ('parent', 'config_id', 'notification_config', ), + 'create_source': ('parent', 'source', ), + 'delete_big_query_export': ('name', ), + 'delete_mute_config': ('name', ), + 'delete_notification_config': ('name', ), + 'delete_resource_value_config': ('name', ), + 'get_big_query_export': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_mute_config': ('name', ), + 'get_notification_config': ('name', ), + 'get_resource_value_config': ('name', ), + 'get_simulation': ('name', ), + 'get_source': ('name', ), + 'get_valued_resource': ('name', ), + 'group_findings': ('parent', 'group_by', 'filter', 'page_token', 'page_size', ), + 'list_attack_paths': ('parent', 'filter', 'page_token', 'page_size', ), + 'list_big_query_exports': ('parent', 'page_size', 'page_token', ), + 'list_findings': ('parent', 'filter', 'order_by', 'field_mask', 'page_token', 'page_size', ), + 'list_mute_configs': ('parent', 'page_size', 'page_token', ), + 'list_notification_configs': ('parent', 'page_token', 'page_size', ), + 'list_resource_value_configs': ('parent', 'page_size', 'page_token', ), + 'list_sources': ('parent', 'page_token', 'page_size', ), + 'list_valued_resources': ('parent', 'filter', 'page_token', 'page_size', 'order_by', ), + 'set_finding_state': ('name', 'state', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), + 'set_mute': ('name', 'mute', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_big_query_export': ('big_query_export', 'update_mask', ), + 'update_external_system': ('external_system', 'update_mask', ), + 'update_finding': ('finding', 'update_mask', ), + 'update_mute_config': ('mute_config', 'update_mask', ), + 'update_notification_config': ('notification_config', 'update_mask', ), + 'update_resource_value_config': ('resource_value_config', 'update_mask', ), + 'update_security_marks': ('security_marks', 'update_mask', ), + 'update_source': ('source', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=securitycenterCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the securitycenter client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/packages/google-cloud-securitycenter/setup.py b/packages/google-cloud-securitycenter/setup.py index f3059947e82c..965683ea548c 100644 --- a/packages/google-cloud-securitycenter/setup.py +++ b/packages/google-cloud-securitycenter/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v1/test_security_center.py b/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v1/test_security_center.py index 862bbc63f28a..f33bc5a05e03 100644 --- a/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v1/test_security_center.py +++ b/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v1/test_security_center.py @@ -93,6 +93,8 @@ kernel_rootkit, kubernetes, label, + load_balancer, + log_entry, mitre_attack, ) from google.cloud.securitycenter_v1.types import external_system as gcs_external_system @@ -114,6 +116,7 @@ from google.cloud.securitycenter_v1.types import mute_config from google.cloud.securitycenter_v1.types import mute_config as gcs_mute_config from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import org_policy from google.cloud.securitycenter_v1.types import organization_settings from google.cloud.securitycenter_v1.types import security_marks from google.cloud.securitycenter_v1.types import securitycenter_service @@ -16229,6 +16232,7 @@ def test_create_finding_rest(request_type): ], }, "yara_rule_signature": {"yara_rule": "yara_rule_value"}, + "signature_type": 1, } ], "uris": ["uris_value1", "uris_value2"], @@ -16249,15 +16253,31 @@ def test_create_finding_rest(request_type): "availability_impact": 1, }, "upstream_fix_available": True, - } + "impact": 1, + "exploitation_activity": 1, + "observed_in_the_wild": True, + "zero_day": True, + }, + "offending_package": { + "package_name": "package_name_value", + "cpe_uri": "cpe_uri_value", + "package_type": "package_type_value", + "package_version": "package_version_value", + }, + "fixed_package": {}, + "security_bulletin": { + "bulletin_id": "bulletin_id_value", + "submission_time": {}, + "suggested_upgrade_version": "suggested_upgrade_version_value", + }, }, "mute_update_time": {}, "external_systems": {}, "mitre_attack": { "primary_tactic": 1, - "primary_techniques": [1], + "primary_techniques": [49], "additional_tactics": [1], - "additional_techniques": [1], + "additional_techniques": [49], "version": "version_value", }, "access": { @@ -16298,6 +16318,10 @@ def test_create_finding_rest(request_type): "hashed_size": 1159, "partially_hashed": True, "contents": "contents_value", + "disk_path": { + "partition_uuid": "partition_uuid_value", + "relative_path": "relative_path_value", + }, }, "libraries": {}, "script": {}, @@ -16327,6 +16351,7 @@ def test_create_finding_rest(request_type): } ], "targets": {}, + "total_exfiltrated_bytes": 2469, }, "iam_bindings": [{"action": 1, "role": "role_value", "member": "member_value"}], "next_steps": "next_steps_value", @@ -16337,6 +16362,7 @@ def test_create_finding_rest(request_type): "uri": "uri_value", "image_id": "image_id_value", "labels": [{"name": "name_value", "value": "value_value"}], + "create_time": {}, } ], "kubernetes": { @@ -16365,6 +16391,15 @@ def test_create_finding_rest(request_type): "version": "version_value", } ], + "objects": [ + { + "group": "group_value", + "kind": "kind_value", + "ns": "ns_value", + "name": "name_value", + "containers": {}, + } + ], }, "database": { "name": "name_value", @@ -16372,6 +16407,7 @@ def test_create_finding_rest(request_type): "user_name": "user_name_value", "query": "query_value", "grantees": ["grantees_value1", "grantees_value2"], + "version": "version_value", }, "files": {}, "cloud_dlp_inspection": { @@ -16395,6 +16431,7 @@ def test_create_finding_rest(request_type): "unexpected_interrupt_handler": True, "unexpected_processes_in_runqueue": True, }, + "org_policies": [{"name": "name_value"}], "application": {"base_uri": "base_uri_value", "full_uri": "full_uri_value"}, "backup_disaster_recovery": { "backup_template": "backup_template_value", @@ -16408,6 +16445,17 @@ def test_create_finding_rest(request_type): "backup_type": "backup_type_value", "backup_create_time": {}, }, + "log_entries": [ + { + "cloud_logging_entry": { + "insert_id": "insert_id_value", + "log_id": "log_id_value", + "resource_container": "resource_container_value", + "timestamp": {}, + } + } + ], + "load_balancers": [{"name": "name_value"}], } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -26144,6 +26192,7 @@ def test_update_finding_rest(request_type): ], }, "yara_rule_signature": {"yara_rule": "yara_rule_value"}, + "signature_type": 1, } ], "uris": ["uris_value1", "uris_value2"], @@ -26164,15 +26213,31 @@ def test_update_finding_rest(request_type): "availability_impact": 1, }, "upstream_fix_available": True, - } + "impact": 1, + "exploitation_activity": 1, + "observed_in_the_wild": True, + "zero_day": True, + }, + "offending_package": { + "package_name": "package_name_value", + "cpe_uri": "cpe_uri_value", + "package_type": "package_type_value", + "package_version": "package_version_value", + }, + "fixed_package": {}, + "security_bulletin": { + "bulletin_id": "bulletin_id_value", + "submission_time": {}, + "suggested_upgrade_version": "suggested_upgrade_version_value", + }, }, "mute_update_time": {}, "external_systems": {}, "mitre_attack": { "primary_tactic": 1, - "primary_techniques": [1], + "primary_techniques": [49], "additional_tactics": [1], - "additional_techniques": [1], + "additional_techniques": [49], "version": "version_value", }, "access": { @@ -26213,6 +26278,10 @@ def test_update_finding_rest(request_type): "hashed_size": 1159, "partially_hashed": True, "contents": "contents_value", + "disk_path": { + "partition_uuid": "partition_uuid_value", + "relative_path": "relative_path_value", + }, }, "libraries": {}, "script": {}, @@ -26242,6 +26311,7 @@ def test_update_finding_rest(request_type): } ], "targets": {}, + "total_exfiltrated_bytes": 2469, }, "iam_bindings": [{"action": 1, "role": "role_value", "member": "member_value"}], "next_steps": "next_steps_value", @@ -26252,6 +26322,7 @@ def test_update_finding_rest(request_type): "uri": "uri_value", "image_id": "image_id_value", "labels": [{"name": "name_value", "value": "value_value"}], + "create_time": {}, } ], "kubernetes": { @@ -26280,6 +26351,15 @@ def test_update_finding_rest(request_type): "version": "version_value", } ], + "objects": [ + { + "group": "group_value", + "kind": "kind_value", + "ns": "ns_value", + "name": "name_value", + "containers": {}, + } + ], }, "database": { "name": "name_value", @@ -26287,6 +26367,7 @@ def test_update_finding_rest(request_type): "user_name": "user_name_value", "query": "query_value", "grantees": ["grantees_value1", "grantees_value2"], + "version": "version_value", }, "files": {}, "cloud_dlp_inspection": { @@ -26310,6 +26391,7 @@ def test_update_finding_rest(request_type): "unexpected_interrupt_handler": True, "unexpected_processes_in_runqueue": True, }, + "org_policies": [{"name": "name_value"}], "application": {"base_uri": "base_uri_value", "full_uri": "full_uri_value"}, "backup_disaster_recovery": { "backup_template": "backup_template_value", @@ -26323,6 +26405,17 @@ def test_update_finding_rest(request_type): "backup_type": "backup_type_value", "backup_create_time": {}, }, + "log_entries": [ + { + "cloud_logging_entry": { + "insert_id": "insert_id_value", + "log_id": "log_id_value", + "resource_container": "resource_container_value", + "timestamp": {}, + } + } + ], + "load_balancers": [{"name": "name_value"}], } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -31252,9 +31345,32 @@ def test_parse_organization_settings_path(): assert expected == actual -def test_security_health_analytics_custom_module_path(): +def test_policy_path(): organization = "oyster" - custom_module = "nudibranch" + constraint_name = "nudibranch" + expected = "organizations/{organization}/policies/{constraint_name}".format( + organization=organization, + constraint_name=constraint_name, + ) + actual = SecurityCenterClient.policy_path(organization, constraint_name) + assert expected == actual + + +def test_parse_policy_path(): + expected = { + "organization": "cuttlefish", + "constraint_name": "mussel", + } + path = SecurityCenterClient.policy_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_policy_path(path) + assert expected == actual + + +def test_security_health_analytics_custom_module_path(): + organization = "winkle" + custom_module = "nautilus" expected = "organizations/{organization}/securityHealthAnalyticsSettings/customModules/{custom_module}".format( organization=organization, custom_module=custom_module, @@ -31267,8 +31383,8 @@ def test_security_health_analytics_custom_module_path(): def test_parse_security_health_analytics_custom_module_path(): expected = { - "organization": "cuttlefish", - "custom_module": "mussel", + "organization": "scallop", + "custom_module": "abalone", } path = SecurityCenterClient.security_health_analytics_custom_module_path(**expected) @@ -31280,8 +31396,8 @@ def test_parse_security_health_analytics_custom_module_path(): def test_security_marks_path(): - organization = "winkle" - asset = "nautilus" + organization = "squid" + asset = "clam" expected = "organizations/{organization}/assets/{asset}/securityMarks".format( organization=organization, asset=asset, @@ -31292,8 +31408,8 @@ def test_security_marks_path(): def test_parse_security_marks_path(): expected = { - "organization": "scallop", - "asset": "abalone", + "organization": "whelk", + "asset": "octopus", } path = SecurityCenterClient.security_marks_path(**expected) @@ -31303,8 +31419,8 @@ def test_parse_security_marks_path(): def test_source_path(): - organization = "squid" - source = "clam" + organization = "oyster" + source = "nudibranch" expected = "organizations/{organization}/sources/{source}".format( organization=organization, source=source, @@ -31315,8 +31431,8 @@ def test_source_path(): def test_parse_source_path(): expected = { - "organization": "whelk", - "source": "octopus", + "organization": "cuttlefish", + "source": "mussel", } path = SecurityCenterClient.source_path(**expected) @@ -31326,8 +31442,8 @@ def test_parse_source_path(): def test_table_data_profile_path(): - project = "oyster" - table_profile = "nudibranch" + project = "winkle" + table_profile = "nautilus" expected = "projects/{project}/tableProfiles/{table_profile}".format( project=project, table_profile=table_profile, @@ -31338,8 +31454,8 @@ def test_table_data_profile_path(): def test_parse_table_data_profile_path(): expected = { - "project": "cuttlefish", - "table_profile": "mussel", + "project": "scallop", + "table_profile": "abalone", } path = SecurityCenterClient.table_data_profile_path(**expected) @@ -31349,8 +31465,8 @@ def test_parse_table_data_profile_path(): def test_topic_path(): - project = "winkle" - topic = "nautilus" + project = "squid" + topic = "clam" expected = "projects/{project}/topics/{topic}".format( project=project, topic=topic, @@ -31361,8 +31477,8 @@ def test_topic_path(): def test_parse_topic_path(): expected = { - "project": "scallop", - "topic": "abalone", + "project": "whelk", + "topic": "octopus", } path = SecurityCenterClient.topic_path(**expected) @@ -31372,7 +31488,7 @@ def test_parse_topic_path(): def test_common_billing_account_path(): - billing_account = "squid" + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -31382,7 +31498,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "clam", + "billing_account": "nudibranch", } path = SecurityCenterClient.common_billing_account_path(**expected) @@ -31392,7 +31508,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "whelk" + folder = "cuttlefish" expected = "folders/{folder}".format( folder=folder, ) @@ -31402,7 +31518,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "octopus", + "folder": "mussel", } path = SecurityCenterClient.common_folder_path(**expected) @@ -31412,7 +31528,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "oyster" + organization = "winkle" expected = "organizations/{organization}".format( organization=organization, ) @@ -31422,7 +31538,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nudibranch", + "organization": "nautilus", } path = SecurityCenterClient.common_organization_path(**expected) @@ -31432,7 +31548,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "cuttlefish" + project = "scallop" expected = "projects/{project}".format( project=project, ) @@ -31442,7 +31558,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "mussel", + "project": "abalone", } path = SecurityCenterClient.common_project_path(**expected) @@ -31452,8 +31568,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "winkle" - location = "nautilus" + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -31464,8 +31580,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "scallop", - "location": "abalone", + "project": "whelk", + "location": "octopus", } path = SecurityCenterClient.common_location_path(**expected) diff --git a/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v2/__init__.py b/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v2/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v2/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# diff --git a/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v2/test_security_center.py b/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v2/test_security_center.py new file mode 100644 index 000000000000..39b042316a49 --- /dev/null +++ b/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v2/test_security_center.py @@ -0,0 +1,29017 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import Iterable +import json +import math + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import operation_async # type: ignore +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +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 empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +from google.cloud.securitycenter_v2.services.security_center import ( + SecurityCenterAsyncClient, + SecurityCenterClient, + pagers, + transports, +) +from google.cloud.securitycenter_v2.types import ( + access, + application, + attack_exposure, + attack_path, + backup_disaster_recovery, + bigquery_export, + cloud_dlp_data_profile, + cloud_dlp_inspection, + compliance, + connection, + contact_details, + container, + database, + exfiltration, +) +from google.cloud.securitycenter_v2.types import ( + iam_binding, + indicator, + kernel_rootkit, + kubernetes, + label, + load_balancer, + log_entry, + mitre_attack, +) +from google.cloud.securitycenter_v2.types import ( + security_posture, + securitycenter_service, + simulation, +) +from google.cloud.securitycenter_v2.types import external_system as gcs_external_system +from google.cloud.securitycenter_v2.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v2.types import ( + resource_value_config as gcs_resource_value_config, +) +from google.cloud.securitycenter_v2.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v2.types import external_system +from google.cloud.securitycenter_v2.types import file +from google.cloud.securitycenter_v2.types import finding +from google.cloud.securitycenter_v2.types import finding as gcs_finding +from google.cloud.securitycenter_v2.types import mute_config +from google.cloud.securitycenter_v2.types import mute_config as gcs_mute_config +from google.cloud.securitycenter_v2.types import notification_config +from google.cloud.securitycenter_v2.types import org_policy, process +from google.cloud.securitycenter_v2.types import resource_value_config +from google.cloud.securitycenter_v2.types import security_marks +from google.cloud.securitycenter_v2.types import source +from google.cloud.securitycenter_v2.types import source as gcs_source +from google.cloud.securitycenter_v2.types import valued_resource, vulnerability + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SecurityCenterClient._get_default_mtls_endpoint(None) is None + assert ( + SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +def test__read_environment_variables(): + assert SecurityCenterClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SecurityCenterClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SecurityCenterClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert SecurityCenterClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SecurityCenterClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SecurityCenterClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert SecurityCenterClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert SecurityCenterClient._get_client_cert_source(None, False) is None + assert ( + SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + SecurityCenterClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + SecurityCenterClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + SecurityCenterClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + SecurityCenterClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SecurityCenterClient), +) +@mock.patch.object( + SecurityCenterAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SecurityCenterAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + SecurityCenterClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + SecurityCenterClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SecurityCenterClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + SecurityCenterClient._get_api_endpoint(None, None, default_universe, "always") + == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SecurityCenterClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SecurityCenterClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + SecurityCenterClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + SecurityCenterClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + SecurityCenterClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + SecurityCenterClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + SecurityCenterClient._get_universe_domain(None, None) + == SecurityCenterClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + SecurityCenterClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "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", + [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), + ], +) +def test_security_center_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "securitycenter.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://securitycenter.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.SecurityCenterGrpcTransport, "grpc"), + (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SecurityCenterRestTransport, "rest"), + ], +) +def test_security_center_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (SecurityCenterClient, "grpc"), + (SecurityCenterAsyncClient, "grpc_asyncio"), + (SecurityCenterClient, "rest"), + ], +) +def test_security_center_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "securitycenter.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://securitycenter.googleapis.com" + ) + + +def test_security_center_client_get_transport_class(): + transport = SecurityCenterClient.get_transport_class() + available_transports = [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterRestTransport, + ] + assert transport in available_transports + + transport = SecurityCenterClient.get_transport_class("grpc") + assert transport == transports.SecurityCenterGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + ( + SecurityCenterAsyncClient, + transports.SecurityCenterGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), + ], +) +@mock.patch.object( + SecurityCenterClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SecurityCenterClient), +) +@mock.patch.object( + SecurityCenterAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SecurityCenterAsyncClient), +) +def test_security_center_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SecurityCenterClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SecurityCenterClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), + ( + SecurityCenterAsyncClient, + transports.SecurityCenterGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), + ( + SecurityCenterAsyncClient, + transports.SecurityCenterGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "true"), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + SecurityCenterClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SecurityCenterClient), +) +@mock.patch.object( + SecurityCenterAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SecurityCenterAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_security_center_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [SecurityCenterClient, SecurityCenterAsyncClient] +) +@mock.patch.object( + SecurityCenterClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SecurityCenterClient), +) +@mock.patch.object( + SecurityCenterAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SecurityCenterAsyncClient), +) +def test_security_center_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize( + "client_class", [SecurityCenterClient, SecurityCenterAsyncClient] +) +@mock.patch.object( + SecurityCenterClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SecurityCenterClient), +) +@mock.patch.object( + SecurityCenterAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SecurityCenterAsyncClient), +) +def test_security_center_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SecurityCenterClient._DEFAULT_UNIVERSE + default_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = SecurityCenterClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + ( + SecurityCenterAsyncClient, + transports.SecurityCenterGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest"), + ], +) +def test_security_center_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + SecurityCenterClient, + transports.SecurityCenterGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SecurityCenterAsyncClient, + transports.SecurityCenterGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (SecurityCenterClient, transports.SecurityCenterRestTransport, "rest", None), + ], +) +def test_security_center_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_security_center_client_client_options_from_dict(): + with mock.patch( + "google.cloud.securitycenter_v2.services.security_center.transports.SecurityCenterGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = SecurityCenterClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + SecurityCenterClient, + transports.SecurityCenterGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SecurityCenterAsyncClient, + transports.SecurityCenterGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_security_center_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "securitycenter.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.BatchCreateResourceValueConfigsRequest, + dict, + ], +) +def test_batch_create_resource_value_configs(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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.batch_create_resource_value_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + securitycenter_service.BatchCreateResourceValueConfigsResponse() + ) + response = client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert ( + args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() + ) + + # Establish that the response is the type that we expect. + assert isinstance( + response, securitycenter_service.BatchCreateResourceValueConfigsResponse + ) + + +def test_batch_create_resource_value_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), "__call__" + ) as call: + client.batch_create_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert ( + args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() + ) + + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest, +): + client = SecurityCenterAsyncClient( + 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.batch_create_resource_value_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.BatchCreateResourceValueConfigsResponse() + ) + response = await client.batch_create_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert ( + args[0] == securitycenter_service.BatchCreateResourceValueConfigsRequest() + ) + + # Establish that the response is the type that we expect. + assert isinstance( + response, securitycenter_service.BatchCreateResourceValueConfigsResponse + ) + + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_async_from_dict(): + await test_batch_create_resource_value_configs_async(request_type=dict) + + +def test_batch_create_resource_value_configs_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.BatchCreateResourceValueConfigsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), "__call__" + ) as call: + call.return_value = ( + securitycenter_service.BatchCreateResourceValueConfigsResponse() + ) + client.batch_create_resource_value_configs(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_batch_create_resource_value_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.BatchCreateResourceValueConfigsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.BatchCreateResourceValueConfigsResponse() + ) + await client.batch_create_resource_value_configs(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_batch_create_resource_value_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + securitycenter_service.BatchCreateResourceValueConfigsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_create_resource_value_configs( + parent="parent_value", + requests=[ + securitycenter_service.CreateResourceValueConfigRequest( + 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 + arg = args[0].requests + mock_val = [ + securitycenter_service.CreateResourceValueConfigRequest( + parent="parent_value" + ) + ] + assert arg == mock_val + + +def test_batch_create_resource_value_configs_flattened_error(): + client = SecurityCenterClient( + 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.batch_create_resource_value_configs( + securitycenter_service.BatchCreateResourceValueConfigsRequest(), + parent="parent_value", + requests=[ + securitycenter_service.CreateResourceValueConfigRequest( + parent="parent_value" + ) + ], + ) + + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_resource_value_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + securitycenter_service.BatchCreateResourceValueConfigsResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.BatchCreateResourceValueConfigsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_create_resource_value_configs( + parent="parent_value", + requests=[ + securitycenter_service.CreateResourceValueConfigRequest( + 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 + arg = args[0].requests + mock_val = [ + securitycenter_service.CreateResourceValueConfigRequest( + parent="parent_value" + ) + ] + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_create_resource_value_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_create_resource_value_configs( + securitycenter_service.BatchCreateResourceValueConfigsRequest(), + parent="parent_value", + requests=[ + securitycenter_service.CreateResourceValueConfigRequest( + parent="parent_value" + ) + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.BulkMuteFindingsRequest, + dict, + ], +) +def test_bulk_mute_findings(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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.bulk_mute_findings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.bulk_mute_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BulkMuteFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_bulk_mute_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), "__call__" + ) as call: + client.bulk_mute_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BulkMuteFindingsRequest() + + +@pytest.mark.asyncio +async def test_bulk_mute_findings_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.BulkMuteFindingsRequest, +): + client = SecurityCenterAsyncClient( + 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.bulk_mute_findings), "__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.bulk_mute_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.BulkMuteFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_bulk_mute_findings_async_from_dict(): + await test_bulk_mute_findings_async(request_type=dict) + + +def test_bulk_mute_findings_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.BulkMuteFindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.bulk_mute_findings(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_bulk_mute_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.BulkMuteFindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.bulk_mute_findings(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_bulk_mute_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), "__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.bulk_mute_findings( + 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_bulk_mute_findings_flattened_error(): + client = SecurityCenterClient( + 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.bulk_mute_findings( + securitycenter_service.BulkMuteFindingsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_bulk_mute_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.bulk_mute_findings), "__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.bulk_mute_findings( + 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_bulk_mute_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.bulk_mute_findings( + securitycenter_service.BulkMuteFindingsRequest(), + parent="parent_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.CreateBigQueryExportRequest, + dict, + ], +) +def test_create_big_query_export(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_big_query_export), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport( + name="name_value", + description="description_value", + filter="filter_value", + dataset="dataset_value", + most_recent_editor="most_recent_editor_value", + principal="principal_value", + ) + response = client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateBigQueryExportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.dataset == "dataset_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.principal == "principal_value" + + +def test_create_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), "__call__" + ) as call: + client.create_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateBigQueryExportRequest() + + +@pytest.mark.asyncio +async def test_create_big_query_export_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.CreateBigQueryExportRequest, +): + client = SecurityCenterAsyncClient( + 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_big_query_export), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigquery_export.BigQueryExport( + name="name_value", + description="description_value", + filter="filter_value", + dataset="dataset_value", + most_recent_editor="most_recent_editor_value", + principal="principal_value", + ) + ) + response = await client.create_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateBigQueryExportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.dataset == "dataset_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.principal == "principal_value" + + +@pytest.mark.asyncio +async def test_create_big_query_export_async_from_dict(): + await test_create_big_query_export_async(request_type=dict) + + +def test_create_big_query_export_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.CreateBigQueryExportRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), "__call__" + ) as call: + call.return_value = bigquery_export.BigQueryExport() + client.create_big_query_export(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_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.CreateBigQueryExportRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigquery_export.BigQueryExport() + ) + await client.create_big_query_export(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_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_big_query_export( + parent="parent_value", + big_query_export=bigquery_export.BigQueryExport(name="name_value"), + big_query_export_id="big_query_export_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].big_query_export + mock_val = bigquery_export.BigQueryExport(name="name_value") + assert arg == mock_val + arg = args[0].big_query_export_id + mock_val = "big_query_export_id_value" + assert arg == mock_val + + +def test_create_big_query_export_flattened_error(): + client = SecurityCenterClient( + 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_big_query_export( + securitycenter_service.CreateBigQueryExportRequest(), + parent="parent_value", + big_query_export=bigquery_export.BigQueryExport(name="name_value"), + big_query_export_id="big_query_export_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_export), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigquery_export.BigQueryExport() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_big_query_export( + parent="parent_value", + big_query_export=bigquery_export.BigQueryExport(name="name_value"), + big_query_export_id="big_query_export_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].big_query_export + mock_val = bigquery_export.BigQueryExport(name="name_value") + assert arg == mock_val + arg = args[0].big_query_export_id + mock_val = "big_query_export_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_big_query_export( + securitycenter_service.CreateBigQueryExportRequest(), + parent="parent_value", + big_query_export=bigquery_export.BigQueryExport(name="name_value"), + big_query_export_id="big_query_export_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.CreateFindingRequest, + dict, + ], +) +def test_create_finding(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_finding), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name="name_value", + canonical_name="canonical_name_value", + parent="parent_value", + resource_name="resource_name_value", + state=gcs_finding.Finding.State.ACTIVE, + category="category_value", + external_uri="external_uri_value", + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator="mute_initiator_value", + parent_display_name="parent_display_name_value", + description="description_value", + next_steps="next_steps_value", + module_name="module_name_value", + ) + response = client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" + assert response.parent == "parent_value" + assert response.resource_name == "resource_name_value" + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == "category_value" + assert response.external_uri == "external_uri_value" + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == "mute_initiator_value" + assert response.parent_display_name == "parent_display_name_value" + assert response.description == "description_value" + assert response.next_steps == "next_steps_value" + assert response.module_name == "module_name_value" + + +def test_create_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_finding), "__call__") as call: + client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + +@pytest.mark.asyncio +async def test_create_finding_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.CreateFindingRequest, +): + client = SecurityCenterAsyncClient( + 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_finding), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_finding.Finding( + name="name_value", + canonical_name="canonical_name_value", + parent="parent_value", + resource_name="resource_name_value", + state=gcs_finding.Finding.State.ACTIVE, + category="category_value", + external_uri="external_uri_value", + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator="mute_initiator_value", + parent_display_name="parent_display_name_value", + description="description_value", + next_steps="next_steps_value", + module_name="module_name_value", + ) + ) + response = await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" + assert response.parent == "parent_value" + assert response.resource_name == "resource_name_value" + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == "category_value" + assert response.external_uri == "external_uri_value" + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == "mute_initiator_value" + assert response.parent_display_name == "parent_display_name_value" + assert response.description == "description_value" + assert response.next_steps == "next_steps_value" + assert response.module_name == "module_name_value" + + +@pytest.mark.asyncio +async def test_create_finding_async_from_dict(): + await test_create_finding_async(request_type=dict) + + +def test_create_finding_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.CreateFindingRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_finding), "__call__") as call: + call.return_value = gcs_finding.Finding() + client.create_finding(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_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.CreateFindingRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_finding), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.create_finding(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_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_finding), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_finding( + parent="parent_value", + finding=gcs_finding.Finding(name="name_value"), + finding_id="finding_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].finding + mock_val = gcs_finding.Finding(name="name_value") + assert arg == mock_val + arg = args[0].finding_id + mock_val = "finding_id_value" + assert arg == mock_val + + +def test_create_finding_flattened_error(): + client = SecurityCenterClient( + 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_finding( + securitycenter_service.CreateFindingRequest(), + parent="parent_value", + finding=gcs_finding.Finding(name="name_value"), + finding_id="finding_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_finding), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_finding( + parent="parent_value", + finding=gcs_finding.Finding(name="name_value"), + finding_id="finding_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].finding + mock_val = gcs_finding.Finding(name="name_value") + assert arg == mock_val + arg = args[0].finding_id + mock_val = "finding_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_finding( + securitycenter_service.CreateFindingRequest(), + parent="parent_value", + finding=gcs_finding.Finding(name="name_value"), + finding_id="finding_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.CreateMuteConfigRequest, + dict, + ], +) +def test_create_mute_config(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_mute_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig( + name="name_value", + description="description_value", + filter="filter_value", + most_recent_editor="most_recent_editor_value", + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + response = client.create_mute_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] == securitycenter_service.CreateMuteConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +def test_create_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), "__call__" + ) as call: + client.create_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateMuteConfigRequest() + + +@pytest.mark.asyncio +async def test_create_mute_config_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.CreateMuteConfigRequest, +): + client = SecurityCenterAsyncClient( + 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_mute_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_mute_config.MuteConfig( + name="name_value", + description="description_value", + filter="filter_value", + most_recent_editor="most_recent_editor_value", + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + ) + response = await client.create_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateMuteConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +@pytest.mark.asyncio +async def test_create_mute_config_async_from_dict(): + await test_create_mute_config_async(request_type=dict) + + +def test_create_mute_config_routing_parameters(): + client = SecurityCenterClient( + 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 = securitycenter_service.CreateMuteConfigRequest( + **{"parent": "projects/sample1/locations/sample2"} + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), "__call__" + ) as call: + call.return_value = gcs_mute_config.MuteConfig() + client.create_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw["metadata"] + # 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 = securitycenter_service.CreateMuteConfigRequest( + **{"parent": "organizations/sample1/locations/sample2"} + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), "__call__" + ) as call: + call.return_value = gcs_mute_config.MuteConfig() + client.create_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw["metadata"] + # 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 = securitycenter_service.CreateMuteConfigRequest( + **{"parent": "folders/sample1/locations/sample2"} + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), "__call__" + ) as call: + call.return_value = gcs_mute_config.MuteConfig() + client.create_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw["metadata"] + + +def test_create_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_mute_config( + parent="parent_value", + mute_config=gcs_mute_config.MuteConfig(name="name_value"), + mute_config_id="mute_config_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].mute_config + mock_val = gcs_mute_config.MuteConfig(name="name_value") + assert arg == mock_val + arg = args[0].mute_config_id + mock_val = "mute_config_id_value" + assert arg == mock_val + + +def test_create_mute_config_flattened_error(): + client = SecurityCenterClient( + 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_mute_config( + securitycenter_service.CreateMuteConfigRequest(), + parent="parent_value", + mute_config=gcs_mute_config.MuteConfig(name="name_value"), + mute_config_id="mute_config_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_mute_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_mute_config.MuteConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_mute_config( + parent="parent_value", + mute_config=gcs_mute_config.MuteConfig(name="name_value"), + mute_config_id="mute_config_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].mute_config + mock_val = gcs_mute_config.MuteConfig(name="name_value") + assert arg == mock_val + arg = args[0].mute_config_id + mock_val = "mute_config_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_mute_config( + securitycenter_service.CreateMuteConfigRequest(), + parent="parent_value", + mute_config=gcs_mute_config.MuteConfig(name="name_value"), + mute_config_id="mute_config_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.CreateNotificationConfigRequest, + dict, + ], +) +def test_create_notification_config(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_notification_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name="name_value", + description="description_value", + pubsub_topic="pubsub_topic_value", + service_account="service_account_value", + ) + response = client.create_notification_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] == securitycenter_service.CreateNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.pubsub_topic == "pubsub_topic_value" + assert response.service_account == "service_account_value" + + +def test_create_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), "__call__" + ) as call: + client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + + +@pytest.mark.asyncio +async def test_create_notification_config_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.CreateNotificationConfigRequest, +): + client = SecurityCenterAsyncClient( + 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_notification_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_notification_config.NotificationConfig( + name="name_value", + description="description_value", + pubsub_topic="pubsub_topic_value", + service_account="service_account_value", + ) + ) + response = await client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.pubsub_topic == "pubsub_topic_value" + assert response.service_account == "service_account_value" + + +@pytest.mark.asyncio +async def test_create_notification_config_async_from_dict(): + await test_create_notification_config_async(request_type=dict) + + +def test_create_notification_config_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.CreateNotificationConfigRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), "__call__" + ) as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.create_notification_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 + + # 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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.CreateNotificationConfigRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_notification_config.NotificationConfig() + ) + await client.create_notification_config(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_notification_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_notification_config( + parent="parent_value", + notification_config=gcs_notification_config.NotificationConfig( + name="name_value" + ), + config_id="config_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].notification_config + mock_val = gcs_notification_config.NotificationConfig(name="name_value") + assert arg == mock_val + arg = args[0].config_id + mock_val = "config_id_value" + assert arg == mock_val + + +def test_create_notification_config_flattened_error(): + client = SecurityCenterClient( + 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_notification_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent="parent_value", + notification_config=gcs_notification_config.NotificationConfig( + name="name_value" + ), + config_id="config_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_notification_config.NotificationConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_notification_config( + parent="parent_value", + notification_config=gcs_notification_config.NotificationConfig( + name="name_value" + ), + config_id="config_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].notification_config + mock_val = gcs_notification_config.NotificationConfig(name="name_value") + assert arg == mock_val + arg = args[0].config_id + mock_val = "config_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_notification_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent="parent_value", + notification_config=gcs_notification_config.NotificationConfig( + name="name_value" + ), + config_id="config_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.CreateSourceRequest, + dict, + ], +) +def test_create_source(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name="name_value", + display_name="display_name_value", + description="description_value", + canonical_name="canonical_name_value", + ) + response = client.create_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] == securitycenter_service.CreateSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" + + +def test_create_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_source), "__call__") as call: + client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + +@pytest.mark.asyncio +async def test_create_source_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.CreateSourceRequest, +): + client = SecurityCenterAsyncClient( + 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_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_source.Source( + name="name_value", + display_name="display_name_value", + description="description_value", + canonical_name="canonical_name_value", + ) + ) + response = await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" + + +@pytest.mark.asyncio +async def test_create_source_async_from_dict(): + await test_create_source_async(request_type=dict) + + +def test_create_source_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.CreateSourceRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_source), "__call__") as call: + call.return_value = gcs_source.Source() + client.create_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.CreateSourceRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_source), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.create_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_source( + parent="parent_value", + source=gcs_source.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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name="name_value") + assert arg == mock_val + + +def test_create_source_flattened_error(): + client = SecurityCenterClient( + 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_source( + securitycenter_service.CreateSourceRequest(), + parent="parent_value", + source=gcs_source.Source(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_source( + parent="parent_value", + source=gcs_source.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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].source + mock_val = gcs_source.Source(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_source( + securitycenter_service.CreateSourceRequest(), + parent="parent_value", + source=gcs_source.Source(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.DeleteBigQueryExportRequest, + dict, + ], +) +def test_delete_big_query_export(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_big_query_export), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), "__call__" + ) as call: + client.delete_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() + + +@pytest.mark.asyncio +async def test_delete_big_query_export_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.DeleteBigQueryExportRequest, +): + client = SecurityCenterAsyncClient( + 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_big_query_export), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteBigQueryExportRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_big_query_export_async_from_dict(): + await test_delete_big_query_export_async(request_type=dict) + + +def test_delete_big_query_export_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.DeleteBigQueryExportRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), "__call__" + ) as call: + call.return_value = None + client.delete_big_query_export(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_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.DeleteBigQueryExportRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_big_query_export(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_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_big_query_export( + 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_delete_big_query_export_flattened_error(): + client = SecurityCenterClient( + 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_big_query_export( + securitycenter_service.DeleteBigQueryExportRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_export), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_big_query_export( + 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_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_big_query_export( + securitycenter_service.DeleteBigQueryExportRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.DeleteMuteConfigRequest, + dict, + ], +) +def test_delete_mute_config(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_mute_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_mute_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] == securitycenter_service.DeleteMuteConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), "__call__" + ) as call: + client.delete_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteMuteConfigRequest() + + +@pytest.mark.asyncio +async def test_delete_mute_config_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.DeleteMuteConfigRequest, +): + client = SecurityCenterAsyncClient( + 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_mute_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteMuteConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_mute_config_async_from_dict(): + await test_delete_mute_config_async(request_type=dict) + + +def test_delete_mute_config_routing_parameters(): + client = SecurityCenterClient( + 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 = securitycenter_service.DeleteMuteConfigRequest( + **{"name": "projects/sample1/locations/sample2/muteConfigs/sample3"} + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), "__call__" + ) as call: + call.return_value = None + client.delete_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw["metadata"] + # 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 = securitycenter_service.DeleteMuteConfigRequest( + **{"name": "organizations/sample1/locations/sample2/muteConfigs/sample3"} + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), "__call__" + ) as call: + call.return_value = None + client.delete_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw["metadata"] + # 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 = securitycenter_service.DeleteMuteConfigRequest( + **{"name": "folders/sample1/locations/sample2/muteConfigs/sample3"} + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), "__call__" + ) as call: + call.return_value = None + client.delete_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw["metadata"] + + +def test_delete_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_mute_config( + 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_delete_mute_config_flattened_error(): + client = SecurityCenterClient( + 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_mute_config( + securitycenter_service.DeleteMuteConfigRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_mute_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_mute_config( + 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_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_mute_config( + securitycenter_service.DeleteMuteConfigRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.DeleteNotificationConfigRequest, + dict, + ], +) +def test_delete_notification_config(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_notification_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_notification_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] == securitycenter_service.DeleteNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), "__call__" + ) as call: + client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + + +@pytest.mark.asyncio +async def test_delete_notification_config_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.DeleteNotificationConfigRequest, +): + client = SecurityCenterAsyncClient( + 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_notification_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_notification_config_async_from_dict(): + await test_delete_notification_config_async(request_type=dict) + + +def test_delete_notification_config_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.DeleteNotificationConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), "__call__" + ) as call: + call.return_value = None + client.delete_notification_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 + + # 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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.DeleteNotificationConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_notification_config(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_notification_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_notification_config( + 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_delete_notification_config_flattened_error(): + client = SecurityCenterClient( + 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_notification_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_notification_config( + 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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_notification_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.DeleteResourceValueConfigRequest, + dict, + ], +) +def test_delete_resource_value_config(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_resource_value_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_resource_value_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] == securitycenter_service.DeleteResourceValueConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_resource_value_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), "__call__" + ) as call: + client.delete_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() + + +@pytest.mark.asyncio +async def test_delete_resource_value_config_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.DeleteResourceValueConfigRequest, +): + client = SecurityCenterAsyncClient( + 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_resource_value_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteResourceValueConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_resource_value_config_async_from_dict(): + await test_delete_resource_value_config_async(request_type=dict) + + +def test_delete_resource_value_config_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.DeleteResourceValueConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), "__call__" + ) as call: + call.return_value = None + client.delete_resource_value_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 + + # 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_resource_value_config_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.DeleteResourceValueConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_resource_value_config(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_resource_value_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_resource_value_config( + 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_delete_resource_value_config_flattened_error(): + client = SecurityCenterClient( + 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_resource_value_config( + securitycenter_service.DeleteResourceValueConfigRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_resource_value_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_resource_value_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_resource_value_config( + 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_resource_value_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_resource_value_config( + securitycenter_service.DeleteResourceValueConfigRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.GetBigQueryExportRequest, + dict, + ], +) +def test_get_big_query_export(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_big_query_export), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport( + name="name_value", + description="description_value", + filter="filter_value", + dataset="dataset_value", + most_recent_editor="most_recent_editor_value", + principal="principal_value", + ) + response = client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetBigQueryExportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.dataset == "dataset_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.principal == "principal_value" + + +def test_get_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), "__call__" + ) as call: + client.get_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetBigQueryExportRequest() + + +@pytest.mark.asyncio +async def test_get_big_query_export_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.GetBigQueryExportRequest, +): + client = SecurityCenterAsyncClient( + 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_big_query_export), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigquery_export.BigQueryExport( + name="name_value", + description="description_value", + filter="filter_value", + dataset="dataset_value", + most_recent_editor="most_recent_editor_value", + principal="principal_value", + ) + ) + response = await client.get_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetBigQueryExportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.dataset == "dataset_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.principal == "principal_value" + + +@pytest.mark.asyncio +async def test_get_big_query_export_async_from_dict(): + await test_get_big_query_export_async(request_type=dict) + + +def test_get_big_query_export_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.GetBigQueryExportRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), "__call__" + ) as call: + call.return_value = bigquery_export.BigQueryExport() + client.get_big_query_export(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_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GetBigQueryExportRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigquery_export.BigQueryExport() + ) + await client.get_big_query_export(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_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_big_query_export( + 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_big_query_export_flattened_error(): + client = SecurityCenterClient( + 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_big_query_export( + securitycenter_service.GetBigQueryExportRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_export), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigquery_export.BigQueryExport() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_big_query_export( + 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_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_big_query_export( + securitycenter_service.GetBigQueryExportRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.GetSimulationRequest, + dict, + ], +) +def test_get_simulation(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_simulation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = simulation.Simulation( + name="name_value", + ) + response = client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSimulationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, simulation.Simulation) + assert response.name == "name_value" + + +def test_get_simulation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_simulation), "__call__") as call: + client.get_simulation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSimulationRequest() + + +@pytest.mark.asyncio +async def test_get_simulation_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.GetSimulationRequest, +): + client = SecurityCenterAsyncClient( + 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_simulation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + simulation.Simulation( + name="name_value", + ) + ) + response = await client.get_simulation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSimulationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, simulation.Simulation) + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_get_simulation_async_from_dict(): + await test_get_simulation_async(request_type=dict) + + +def test_get_simulation_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.GetSimulationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_simulation), "__call__") as call: + call.return_value = simulation.Simulation() + client.get_simulation(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_simulation_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GetSimulationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_simulation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + simulation.Simulation() + ) + await client.get_simulation(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_simulation_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_simulation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = simulation.Simulation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_simulation( + 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_simulation_flattened_error(): + client = SecurityCenterClient( + 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_simulation( + securitycenter_service.GetSimulationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_simulation_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_simulation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = simulation.Simulation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + simulation.Simulation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_simulation( + 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_simulation_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_simulation( + securitycenter_service.GetSimulationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.GetValuedResourceRequest, + dict, + ], +) +def test_get_valued_resource(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_valued_resource), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = valued_resource.ValuedResource( + name="name_value", + resource="resource_value", + resource_type="resource_type_value", + display_name="display_name_value", + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + ) + response = client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetValuedResourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, valued_resource.ValuedResource) + assert response.name == "name_value" + assert response.resource == "resource_value" + assert response.resource_type == "resource_type_value" + assert response.display_name == "display_name_value" + assert ( + response.resource_value + == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW + ) + assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) + + +def test_get_valued_resource_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), "__call__" + ) as call: + client.get_valued_resource() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetValuedResourceRequest() + + +@pytest.mark.asyncio +async def test_get_valued_resource_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.GetValuedResourceRequest, +): + client = SecurityCenterAsyncClient( + 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_valued_resource), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + valued_resource.ValuedResource( + name="name_value", + resource="resource_value", + resource_type="resource_type_value", + display_name="display_name_value", + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + ) + ) + response = await client.get_valued_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetValuedResourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, valued_resource.ValuedResource) + assert response.name == "name_value" + assert response.resource == "resource_value" + assert response.resource_type == "resource_type_value" + assert response.display_name == "display_name_value" + assert ( + response.resource_value + == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW + ) + assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) + + +@pytest.mark.asyncio +async def test_get_valued_resource_async_from_dict(): + await test_get_valued_resource_async(request_type=dict) + + +def test_get_valued_resource_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.GetValuedResourceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), "__call__" + ) as call: + call.return_value = valued_resource.ValuedResource() + client.get_valued_resource(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_valued_resource_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GetValuedResourceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + valued_resource.ValuedResource() + ) + await client.get_valued_resource(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_valued_resource_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = valued_resource.ValuedResource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_valued_resource( + 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_valued_resource_flattened_error(): + client = SecurityCenterClient( + 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_valued_resource( + securitycenter_service.GetValuedResourceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_valued_resource_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_valued_resource), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = valued_resource.ValuedResource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + valued_resource.ValuedResource() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_valued_resource( + 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_valued_resource_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_valued_resource( + securitycenter_service.GetValuedResourceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest +): + client = SecurityCenterAsyncClient( + 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_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = SecurityCenterClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + + request.resource = "resource_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.get_iam_policy(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", + "resource=resource_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + + request.resource = "resource_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + await client.get_iam_policy(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", + "resource=resource_value", + ) in kw["metadata"] + + +def test_get_iam_policy_from_dict_foreign(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource="resource_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].resource + mock_val = "resource_value" + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = SecurityCenterClient( + 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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource="resource_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].resource + mock_val = "resource_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource="resource_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.GetMuteConfigRequest, + dict, + ], +) +def test_get_mute_config(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_mute_config), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = mute_config.MuteConfig( + name="name_value", + description="description_value", + filter="filter_value", + most_recent_editor="most_recent_editor_value", + type_=mute_config.MuteConfig.MuteConfigType.STATIC, + ) + response = client.get_mute_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] == securitycenter_service.GetMuteConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, mute_config.MuteConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC + + +def test_get_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_mute_config), "__call__") as call: + client.get_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetMuteConfigRequest() + + +@pytest.mark.asyncio +async def test_get_mute_config_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.GetMuteConfigRequest, +): + client = SecurityCenterAsyncClient( + 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_mute_config), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + mute_config.MuteConfig( + name="name_value", + description="description_value", + filter="filter_value", + most_recent_editor="most_recent_editor_value", + type_=mute_config.MuteConfig.MuteConfigType.STATIC, + ) + ) + response = await client.get_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetMuteConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, mute_config.MuteConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC + + +@pytest.mark.asyncio +async def test_get_mute_config_async_from_dict(): + await test_get_mute_config_async(request_type=dict) + + +def test_get_mute_config_routing_parameters(): + client = SecurityCenterClient( + 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 = securitycenter_service.GetMuteConfigRequest( + **{"name": "projects/sample1/locations/sample2/muteConfigs/sample3"} + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_mute_config), "__call__") as call: + call.return_value = mute_config.MuteConfig() + client.get_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw["metadata"] + # 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 = securitycenter_service.GetMuteConfigRequest( + **{"name": "organizations/sample1/locations/sample2/muteConfigs/sample3"} + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_mute_config), "__call__") as call: + call.return_value = mute_config.MuteConfig() + client.get_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw["metadata"] + # 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 = securitycenter_service.GetMuteConfigRequest( + **{"name": "folders/sample1/locations/sample2/muteConfigs/sample3"} + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_mute_config), "__call__") as call: + call.return_value = mute_config.MuteConfig() + client.get_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw["metadata"] + + +def test_get_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_mute_config), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = mute_config.MuteConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_mute_config( + 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_mute_config_flattened_error(): + client = SecurityCenterClient( + 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_mute_config( + securitycenter_service.GetMuteConfigRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_mute_config), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = mute_config.MuteConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + mute_config.MuteConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_mute_config( + 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_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_mute_config( + securitycenter_service.GetMuteConfigRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.GetNotificationConfigRequest, + dict, + ], +) +def test_get_notification_config(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_notification_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig( + name="name_value", + description="description_value", + pubsub_topic="pubsub_topic_value", + service_account="service_account_value", + ) + response = client.get_notification_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] == securitycenter_service.GetNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.pubsub_topic == "pubsub_topic_value" + assert response.service_account == "service_account_value" + + +def test_get_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), "__call__" + ) as call: + client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + + +@pytest.mark.asyncio +async def test_get_notification_config_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.GetNotificationConfigRequest, +): + client = SecurityCenterAsyncClient( + 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_notification_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + notification_config.NotificationConfig( + name="name_value", + description="description_value", + pubsub_topic="pubsub_topic_value", + service_account="service_account_value", + ) + ) + response = await client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.pubsub_topic == "pubsub_topic_value" + assert response.service_account == "service_account_value" + + +@pytest.mark.asyncio +async def test_get_notification_config_async_from_dict(): + await test_get_notification_config_async(request_type=dict) + + +def test_get_notification_config_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.GetNotificationConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), "__call__" + ) as call: + call.return_value = notification_config.NotificationConfig() + client.get_notification_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 + + # 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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GetNotificationConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + notification_config.NotificationConfig() + ) + await client.get_notification_config(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_notification_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_notification_config( + 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_notification_config_flattened_error(): + client = SecurityCenterClient( + 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_notification_config( + securitycenter_service.GetNotificationConfigRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + notification_config.NotificationConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_notification_config( + 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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_notification_config( + securitycenter_service.GetNotificationConfigRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.GetResourceValueConfigRequest, + dict, + ], +) +def test_get_resource_value_config(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_resource_value_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resource_value_config.ResourceValueConfig( + name="name_value", + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=["tag_values_value"], + resource_type="resource_type_value", + scope="scope_value", + description="description_value", + ) + response = client.get_resource_value_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] == securitycenter_service.GetResourceValueConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resource_value_config.ResourceValueConfig) + assert response.name == "name_value" + assert response.resource_value == resource_value_config.ResourceValue.HIGH + assert response.tag_values == ["tag_values_value"] + assert response.resource_type == "resource_type_value" + assert response.scope == "scope_value" + assert response.description == "description_value" + + +def test_get_resource_value_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), "__call__" + ) as call: + client.get_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetResourceValueConfigRequest() + + +@pytest.mark.asyncio +async def test_get_resource_value_config_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.GetResourceValueConfigRequest, +): + client = SecurityCenterAsyncClient( + 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_resource_value_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource_value_config.ResourceValueConfig( + name="name_value", + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=["tag_values_value"], + resource_type="resource_type_value", + scope="scope_value", + description="description_value", + ) + ) + response = await client.get_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetResourceValueConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resource_value_config.ResourceValueConfig) + assert response.name == "name_value" + assert response.resource_value == resource_value_config.ResourceValue.HIGH + assert response.tag_values == ["tag_values_value"] + assert response.resource_type == "resource_type_value" + assert response.scope == "scope_value" + assert response.description == "description_value" + + +@pytest.mark.asyncio +async def test_get_resource_value_config_async_from_dict(): + await test_get_resource_value_config_async(request_type=dict) + + +def test_get_resource_value_config_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.GetResourceValueConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), "__call__" + ) as call: + call.return_value = resource_value_config.ResourceValueConfig() + client.get_resource_value_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 + + # 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_resource_value_config_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GetResourceValueConfigRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource_value_config.ResourceValueConfig() + ) + await client.get_resource_value_config(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_resource_value_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resource_value_config.ResourceValueConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_resource_value_config( + 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_resource_value_config_flattened_error(): + client = SecurityCenterClient( + 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_resource_value_config( + securitycenter_service.GetResourceValueConfigRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_resource_value_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_value_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resource_value_config.ResourceValueConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resource_value_config.ResourceValueConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_resource_value_config( + 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_resource_value_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_resource_value_config( + securitycenter_service.GetResourceValueConfigRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.GetSourceRequest, + dict, + ], +) +def test_get_source(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source( + name="name_value", + display_name="display_name_value", + description="description_value", + canonical_name="canonical_name_value", + ) + response = client.get_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] == securitycenter_service.GetSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" + + +def test_get_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_source), "__call__") as call: + client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + +@pytest.mark.asyncio +async def test_get_source_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.GetSourceRequest, +): + client = SecurityCenterAsyncClient( + 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_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + source.Source( + name="name_value", + display_name="display_name_value", + description="description_value", + canonical_name="canonical_name_value", + ) + ) + response = await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" + + +@pytest.mark.asyncio +async def test_get_source_async_from_dict(): + await test_get_source_async(request_type=dict) + + +def test_get_source_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.GetSourceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_source), "__call__") as call: + call.return_value = source.Source() + client.get_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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GetSourceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_source), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + await client.get_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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_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_source_flattened_error(): + client = SecurityCenterClient( + 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_source( + securitycenter_service.GetSourceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_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_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_source( + securitycenter_service.GetSourceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.GroupFindingsRequest, + dict, + ], +) +def test_group_findings(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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.group_findings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + response = client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +def test_group_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.group_findings), "__call__") as call: + client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + +@pytest.mark.asyncio +async def test_group_findings_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.GroupFindingsRequest, +): + client = SecurityCenterAsyncClient( + 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.group_findings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.GroupFindingsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + ) + response = await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_group_findings_async_from_dict(): + await test_group_findings_async(request_type=dict) + + +def test_group_findings_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.GroupFindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.group_findings), "__call__") as call: + call.return_value = securitycenter_service.GroupFindingsResponse() + client.group_findings(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_group_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.GroupFindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.group_findings), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.GroupFindingsResponse() + ) + await client.group_findings(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_group_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.group_findings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.group_findings( + parent="parent_value", + group_by="group_by_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].group_by + mock_val = "group_by_value" + assert arg == mock_val + + +def test_group_findings_flattened_error(): + client = SecurityCenterClient( + 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.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent="parent_value", + group_by="group_by_value", + ) + + +@pytest.mark.asyncio +async def test_group_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.group_findings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.GroupFindingsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.group_findings( + parent="parent_value", + group_by="group_by_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].group_by + mock_val = "group_by_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_group_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent="parent_value", + group_by="group_by_value", + ) + + +def test_group_findings_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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.group_findings), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token="abc", + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token="def", + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token="ghi", + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.group_findings(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) for i in results) + + +def test_group_findings_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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.group_findings), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token="abc", + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token="def", + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token="ghi", + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_findings(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_group_findings_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token="abc", + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token="def", + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token="ghi", + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_findings( + 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, securitycenter_service.GroupResult) for i in responses) + + +@pytest.mark.asyncio +async def test_group_findings_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token="abc", + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token="def", + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token="ghi", + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + 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.group_findings(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", + [ + securitycenter_service.ListAttackPathsRequest, + dict, + ], +) +def test_list_attack_paths(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_attack_paths), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAttackPathsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAttackPathsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttackPathsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_attack_paths_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), "__call__" + ) as call: + client.list_attack_paths() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAttackPathsRequest() + + +@pytest.mark.asyncio +async def test_list_attack_paths_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.ListAttackPathsRequest, +): + client = SecurityCenterAsyncClient( + 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_attack_paths), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListAttackPathsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_attack_paths(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAttackPathsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttackPathsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_attack_paths_async_from_dict(): + await test_list_attack_paths_async(request_type=dict) + + +def test_list_attack_paths_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.ListAttackPathsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), "__call__" + ) as call: + call.return_value = securitycenter_service.ListAttackPathsResponse() + client.list_attack_paths(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_attack_paths_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListAttackPathsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListAttackPathsResponse() + ) + await client.list_attack_paths(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_attack_paths_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAttackPathsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_attack_paths( + 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_attack_paths_flattened_error(): + client = SecurityCenterClient( + 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_attack_paths( + securitycenter_service.ListAttackPathsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_attack_paths_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAttackPathsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListAttackPathsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_attack_paths( + 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_attack_paths_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_attack_paths( + securitycenter_service.ListAttackPathsRequest(), + parent="parent_value", + ) + + +def test_list_attack_paths_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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_attack_paths), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token="abc", + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token="def", + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_attack_paths(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, attack_path.AttackPath) for i in results) + + +def test_list_attack_paths_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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_attack_paths), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token="abc", + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token="def", + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + RuntimeError, + ) + pages = list(client.list_attack_paths(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_attack_paths_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token="abc", + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token="def", + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_attack_paths( + 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, attack_path.AttackPath) for i in responses) + + +@pytest.mark.asyncio +async def test_list_attack_paths_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_attack_paths), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token="abc", + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token="def", + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + 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_attack_paths(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", + [ + securitycenter_service.ListBigQueryExportsRequest, + dict, + ], +) +def test_list_big_query_exports(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_big_query_exports), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListBigQueryExportsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListBigQueryExportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryExportsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_big_query_exports_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), "__call__" + ) as call: + client.list_big_query_exports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListBigQueryExportsRequest() + + +@pytest.mark.asyncio +async def test_list_big_query_exports_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.ListBigQueryExportsRequest, +): + client = SecurityCenterAsyncClient( + 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_big_query_exports), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListBigQueryExportsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_big_query_exports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListBigQueryExportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryExportsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_big_query_exports_async_from_dict(): + await test_list_big_query_exports_async(request_type=dict) + + +def test_list_big_query_exports_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.ListBigQueryExportsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), "__call__" + ) as call: + call.return_value = securitycenter_service.ListBigQueryExportsResponse() + client.list_big_query_exports(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_big_query_exports_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListBigQueryExportsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListBigQueryExportsResponse() + ) + await client.list_big_query_exports(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_big_query_exports_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListBigQueryExportsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_big_query_exports( + 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_big_query_exports_flattened_error(): + client = SecurityCenterClient( + 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_big_query_exports( + securitycenter_service.ListBigQueryExportsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_big_query_exports_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListBigQueryExportsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListBigQueryExportsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_big_query_exports( + 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_big_query_exports_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_big_query_exports( + securitycenter_service.ListBigQueryExportsRequest(), + parent="parent_value", + ) + + +def test_list_big_query_exports_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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_big_query_exports), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token="abc", + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token="def", + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_big_query_exports(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, bigquery_export.BigQueryExport) for i in results) + + +def test_list_big_query_exports_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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_big_query_exports), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token="abc", + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token="def", + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + RuntimeError, + ) + pages = list(client.list_big_query_exports(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_big_query_exports_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token="abc", + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token="def", + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_big_query_exports( + 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, bigquery_export.BigQueryExport) for i in responses) + + +@pytest.mark.asyncio +async def test_list_big_query_exports_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_exports), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token="abc", + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token="def", + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + 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_big_query_exports(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", + [ + securitycenter_service.ListFindingsRequest, + dict, + ], +) +def test_list_findings(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_findings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListFindingsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + response = client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +def test_list_findings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_findings), "__call__") as call: + client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + +@pytest.mark.asyncio +async def test_list_findings_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.ListFindingsRequest, +): + client = SecurityCenterAsyncClient( + 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_findings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListFindingsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + ) + response = await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_findings_async_from_dict(): + await test_list_findings_async(request_type=dict) + + +def test_list_findings_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.ListFindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_findings), "__call__") as call: + call.return_value = securitycenter_service.ListFindingsResponse() + client.list_findings(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_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListFindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_findings), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListFindingsResponse() + ) + await client.list_findings(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_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_findings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_findings( + 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_findings_flattened_error(): + client = SecurityCenterClient( + 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_findings( + securitycenter_service.ListFindingsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_findings), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListFindingsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_findings( + 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_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_findings( + securitycenter_service.ListFindingsRequest(), + parent="parent_value", + ) + + +def test_list_findings_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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_findings), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token="abc", + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token="def", + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_findings(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance( + i, securitycenter_service.ListFindingsResponse.ListFindingsResult + ) + for i in results + ) + + +def test_list_findings_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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_findings), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token="abc", + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token="def", + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_findings(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_findings_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token="abc", + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token="def", + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_findings( + 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, securitycenter_service.ListFindingsResponse.ListFindingsResult + ) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_findings_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token="abc", + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token="def", + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + 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_findings(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", + [ + securitycenter_service.ListMuteConfigsRequest, + dict, + ], +) +def test_list_mute_configs(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_mute_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListMuteConfigsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListMuteConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMuteConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_mute_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), "__call__" + ) as call: + client.list_mute_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListMuteConfigsRequest() + + +@pytest.mark.asyncio +async def test_list_mute_configs_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.ListMuteConfigsRequest, +): + client = SecurityCenterAsyncClient( + 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_mute_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListMuteConfigsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_mute_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListMuteConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMuteConfigsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_mute_configs_async_from_dict(): + await test_list_mute_configs_async(request_type=dict) + + +def test_list_mute_configs_routing_parameters(): + client = SecurityCenterClient( + 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 = securitycenter_service.ListMuteConfigsRequest( + **{"parent": "projects/sample1/locations/sample2/muteConfigs"} + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), "__call__" + ) as call: + call.return_value = securitycenter_service.ListMuteConfigsResponse() + client.list_mute_configs(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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw["metadata"] + # 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 = securitycenter_service.ListMuteConfigsRequest( + **{"parent": "organizations/sample1/locations/sample2/muteConfigs"} + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), "__call__" + ) as call: + call.return_value = securitycenter_service.ListMuteConfigsResponse() + client.list_mute_configs(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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw["metadata"] + # 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 = securitycenter_service.ListMuteConfigsRequest( + **{"parent": "folders/sample1/locations/sample2/muteConfigs"} + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), "__call__" + ) as call: + call.return_value = securitycenter_service.ListMuteConfigsResponse() + client.list_mute_configs(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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw["metadata"] + + +def test_list_mute_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListMuteConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_mute_configs( + 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_mute_configs_flattened_error(): + client = SecurityCenterClient( + 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_mute_configs( + securitycenter_service.ListMuteConfigsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_mute_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListMuteConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListMuteConfigsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_mute_configs( + 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_mute_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_mute_configs( + securitycenter_service.ListMuteConfigsRequest(), + parent="parent_value", + ) + + +def test_list_mute_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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_mute_configs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token="abc", + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token="def", + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.list_mute_configs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, mute_config.MuteConfig) for i in results) + + +def test_list_mute_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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_mute_configs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token="abc", + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token="def", + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_mute_configs(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_mute_configs_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token="abc", + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token="def", + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_mute_configs( + 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, mute_config.MuteConfig) for i in responses) + + +@pytest.mark.asyncio +async def test_list_mute_configs_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_mute_configs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token="abc", + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token="def", + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + 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_mute_configs(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", + [ + securitycenter_service.ListNotificationConfigsRequest, + dict, + ], +) +def test_list_notification_configs(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_notification_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_notification_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), "__call__" + ) as call: + client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + +@pytest.mark.asyncio +async def test_list_notification_configs_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.ListNotificationConfigsRequest, +): + client = SecurityCenterAsyncClient( + 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_notification_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListNotificationConfigsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_notification_configs_async_from_dict(): + await test_list_notification_configs_async(request_type=dict) + + +def test_list_notification_configs_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.ListNotificationConfigsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), "__call__" + ) as call: + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + client.list_notification_configs(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_notification_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListNotificationConfigsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListNotificationConfigsResponse() + ) + await client.list_notification_configs(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_notification_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_notification_configs( + 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_notification_configs_flattened_error(): + client = SecurityCenterClient( + 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_notification_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_notification_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListNotificationConfigsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_notification_configs( + 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_notification_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_notification_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent="parent_value", + ) + + +def test_list_notification_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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_notification_configs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token="abc", + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token="def", + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_notification_configs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, notification_config.NotificationConfig) for i in results + ) + + +def test_list_notification_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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_notification_configs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token="abc", + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token="def", + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_notification_configs(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_notification_configs_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token="abc", + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token="def", + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_notification_configs( + 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, notification_config.NotificationConfig) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_notification_configs_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token="abc", + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token="def", + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + 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_notification_configs(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", + [ + securitycenter_service.ListResourceValueConfigsRequest, + dict, + ], +) +def test_list_resource_value_configs(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_resource_value_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListResourceValueConfigsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceValueConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_resource_value_configs_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), "__call__" + ) as call: + client.list_resource_value_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() + + +@pytest.mark.asyncio +async def test_list_resource_value_configs_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.ListResourceValueConfigsRequest, +): + client = SecurityCenterAsyncClient( + 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_resource_value_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListResourceValueConfigsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_resource_value_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListResourceValueConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceValueConfigsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_resource_value_configs_async_from_dict(): + await test_list_resource_value_configs_async(request_type=dict) + + +def test_list_resource_value_configs_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.ListResourceValueConfigsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), "__call__" + ) as call: + call.return_value = securitycenter_service.ListResourceValueConfigsResponse() + client.list_resource_value_configs(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_resource_value_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListResourceValueConfigsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListResourceValueConfigsResponse() + ) + await client.list_resource_value_configs(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_resource_value_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListResourceValueConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_resource_value_configs( + 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_resource_value_configs_flattened_error(): + client = SecurityCenterClient( + 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_resource_value_configs( + securitycenter_service.ListResourceValueConfigsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_resource_value_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListResourceValueConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListResourceValueConfigsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_resource_value_configs( + 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_resource_value_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_resource_value_configs( + securitycenter_service.ListResourceValueConfigsRequest(), + parent="parent_value", + ) + + +def test_list_resource_value_configs_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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_resource_value_configs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token="abc", + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token="def", + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_resource_value_configs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, resource_value_config.ResourceValueConfig) for i in results + ) + + +def test_list_resource_value_configs_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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_resource_value_configs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token="abc", + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token="def", + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_resource_value_configs(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_resource_value_configs_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token="abc", + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token="def", + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_resource_value_configs( + 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, resource_value_config.ResourceValueConfig) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_resource_value_configs_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_value_configs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token="abc", + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token="def", + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + 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_resource_value_configs(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", + [ + securitycenter_service.ListSourcesRequest, + dict, + ], +) +def test_list_sources(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_sources), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_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] == securitycenter_service.ListSourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_sources_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sources), "__call__") as call: + client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + +@pytest.mark.asyncio +async def test_list_sources_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.ListSourcesRequest, +): + client = SecurityCenterAsyncClient( + 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_sources), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListSourcesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_sources_async_from_dict(): + await test_list_sources_async(request_type=dict) + + +def test_list_sources_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.ListSourcesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sources), "__call__") as call: + call.return_value = securitycenter_service.ListSourcesResponse() + client.list_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_sources_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListSourcesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sources), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListSourcesResponse() + ) + await client.list_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_sources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sources), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_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_sources_flattened_error(): + client = SecurityCenterClient( + 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_sources( + securitycenter_service.ListSourcesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_sources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sources), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListSourcesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_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_sources_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_sources( + securitycenter_service.ListSourcesRequest(), + parent="parent_value", + ) + + +def test_list_sources_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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_sources), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token="abc", + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token="def", + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_sources(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, source.Source) for i in results) + + +def test_list_sources_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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_sources), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token="abc", + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token="def", + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + pages = list(client.list_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_sources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token="abc", + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token="def", + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_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, source.Source) for i in responses) + + +@pytest.mark.asyncio +async def test_list_sources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token="abc", + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token="def", + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + 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_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", + [ + securitycenter_service.ListValuedResourcesRequest, + dict, + ], +) +def test_list_valued_resources(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_valued_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListValuedResourcesResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + response = client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListValuedResourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListValuedResourcesPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +def test_list_valued_resources_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), "__call__" + ) as call: + client.list_valued_resources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListValuedResourcesRequest() + + +@pytest.mark.asyncio +async def test_list_valued_resources_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.ListValuedResourcesRequest, +): + client = SecurityCenterAsyncClient( + 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_valued_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListValuedResourcesResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + ) + response = await client.list_valued_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListValuedResourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListValuedResourcesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_valued_resources_async_from_dict(): + await test_list_valued_resources_async(request_type=dict) + + +def test_list_valued_resources_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.ListValuedResourcesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), "__call__" + ) as call: + call.return_value = securitycenter_service.ListValuedResourcesResponse() + client.list_valued_resources(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_valued_resources_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.ListValuedResourcesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListValuedResourcesResponse() + ) + await client.list_valued_resources(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_valued_resources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListValuedResourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_valued_resources( + 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_valued_resources_flattened_error(): + client = SecurityCenterClient( + 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_valued_resources( + securitycenter_service.ListValuedResourcesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_valued_resources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListValuedResourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + securitycenter_service.ListValuedResourcesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_valued_resources( + 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_valued_resources_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_valued_resources( + securitycenter_service.ListValuedResourcesRequest(), + parent="parent_value", + ) + + +def test_list_valued_resources_pager(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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_valued_resources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token="abc", + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token="def", + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_valued_resources(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, valued_resource.ValuedResource) for i in results) + + +def test_list_valued_resources_pages(transport_name: str = "grpc"): + client = SecurityCenterClient( + 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_valued_resources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token="abc", + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token="def", + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + RuntimeError, + ) + pages = list(client.list_valued_resources(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_valued_resources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token="abc", + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token="def", + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_valued_resources( + 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, valued_resource.ValuedResource) for i in responses) + + +@pytest.mark.asyncio +async def test_list_valued_resources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_valued_resources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token="abc", + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token="def", + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + 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_valued_resources(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", + [ + securitycenter_service.SetFindingStateRequest, + dict, + ], +) +def test_set_finding_state(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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.set_finding_state), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name="name_value", + canonical_name="canonical_name_value", + parent="parent_value", + resource_name="resource_name_value", + state=finding.Finding.State.ACTIVE, + category="category_value", + external_uri="external_uri_value", + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator="mute_initiator_value", + parent_display_name="parent_display_name_value", + description="description_value", + next_steps="next_steps_value", + module_name="module_name_value", + ) + response = client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" + assert response.parent == "parent_value" + assert response.resource_name == "resource_name_value" + assert response.state == finding.Finding.State.ACTIVE + assert response.category == "category_value" + assert response.external_uri == "external_uri_value" + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == "mute_initiator_value" + assert response.parent_display_name == "parent_display_name_value" + assert response.description == "description_value" + assert response.next_steps == "next_steps_value" + assert response.module_name == "module_name_value" + + +def test_set_finding_state_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), "__call__" + ) as call: + client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + +@pytest.mark.asyncio +async def test_set_finding_state_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.SetFindingStateRequest, +): + client = SecurityCenterAsyncClient( + 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.set_finding_state), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + finding.Finding( + name="name_value", + canonical_name="canonical_name_value", + parent="parent_value", + resource_name="resource_name_value", + state=finding.Finding.State.ACTIVE, + category="category_value", + external_uri="external_uri_value", + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator="mute_initiator_value", + parent_display_name="parent_display_name_value", + description="description_value", + next_steps="next_steps_value", + module_name="module_name_value", + ) + ) + response = await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" + assert response.parent == "parent_value" + assert response.resource_name == "resource_name_value" + assert response.state == finding.Finding.State.ACTIVE + assert response.category == "category_value" + assert response.external_uri == "external_uri_value" + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == "mute_initiator_value" + assert response.parent_display_name == "parent_display_name_value" + assert response.description == "description_value" + assert response.next_steps == "next_steps_value" + assert response.module_name == "module_name_value" + + +@pytest.mark.asyncio +async def test_set_finding_state_async_from_dict(): + await test_set_finding_state_async(request_type=dict) + + +def test_set_finding_state_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.SetFindingStateRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), "__call__" + ) as call: + call.return_value = finding.Finding() + client.set_finding_state(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_set_finding_state_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.SetFindingStateRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_finding_state(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_set_finding_state_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_finding_state( + name="name_value", + state=finding.Finding.State.ACTIVE, + ) + + # 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].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + + +def test_set_finding_state_flattened_error(): + client = SecurityCenterClient( + 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.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name="name_value", + state=finding.Finding.State.ACTIVE, + ) + + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_finding_state( + name="name_value", + state=finding.Finding.State.ACTIVE, + ) + + # 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].state + mock_val = finding.Finding.State.ACTIVE + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name="name_value", + state=finding.Finding.State.ACTIVE, + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest +): + client = SecurityCenterAsyncClient( + 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.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = SecurityCenterClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + + request.resource = "resource_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + client.set_iam_policy(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", + "resource=resource_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + + request.resource = "resource_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + await client.set_iam_policy(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", + "resource=resource_value", + ) in kw["metadata"] + + +def test_set_iam_policy_from_dict_foreign(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + "update_mask": field_mask_pb2.FieldMask(paths=["paths_value"]), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource="resource_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].resource + mock_val = "resource_value" + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = SecurityCenterClient( + 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.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource="resource_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].resource + mock_val = "resource_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource="resource_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.SetMuteRequest, + dict, + ], +) +def test_set_mute(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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.set_mute), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name="name_value", + canonical_name="canonical_name_value", + parent="parent_value", + resource_name="resource_name_value", + state=finding.Finding.State.ACTIVE, + category="category_value", + external_uri="external_uri_value", + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator="mute_initiator_value", + parent_display_name="parent_display_name_value", + description="description_value", + next_steps="next_steps_value", + module_name="module_name_value", + ) + response = client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetMuteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" + assert response.parent == "parent_value" + assert response.resource_name == "resource_name_value" + assert response.state == finding.Finding.State.ACTIVE + assert response.category == "category_value" + assert response.external_uri == "external_uri_value" + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == "mute_initiator_value" + assert response.parent_display_name == "parent_display_name_value" + assert response.description == "description_value" + assert response.next_steps == "next_steps_value" + assert response.module_name == "module_name_value" + + +def test_set_mute_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_mute), "__call__") as call: + client.set_mute() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetMuteRequest() + + +@pytest.mark.asyncio +async def test_set_mute_async( + transport: str = "grpc_asyncio", request_type=securitycenter_service.SetMuteRequest +): + client = SecurityCenterAsyncClient( + 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.set_mute), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + finding.Finding( + name="name_value", + canonical_name="canonical_name_value", + parent="parent_value", + resource_name="resource_name_value", + state=finding.Finding.State.ACTIVE, + category="category_value", + external_uri="external_uri_value", + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator="mute_initiator_value", + parent_display_name="parent_display_name_value", + description="description_value", + next_steps="next_steps_value", + module_name="module_name_value", + ) + ) + response = await client.set_mute(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetMuteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" + assert response.parent == "parent_value" + assert response.resource_name == "resource_name_value" + assert response.state == finding.Finding.State.ACTIVE + assert response.category == "category_value" + assert response.external_uri == "external_uri_value" + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == "mute_initiator_value" + assert response.parent_display_name == "parent_display_name_value" + assert response.description == "description_value" + assert response.next_steps == "next_steps_value" + assert response.module_name == "module_name_value" + + +@pytest.mark.asyncio +async def test_set_mute_async_from_dict(): + await test_set_mute_async(request_type=dict) + + +def test_set_mute_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.SetMuteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_mute), "__call__") as call: + call.return_value = finding.Finding() + client.set_mute(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_set_mute_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.SetMuteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_mute), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_mute(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_set_mute_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_mute), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_mute( + name="name_value", + mute=finding.Finding.Mute.MUTED, + ) + + # 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].mute + mock_val = finding.Finding.Mute.MUTED + assert arg == mock_val + + +def test_set_mute_flattened_error(): + client = SecurityCenterClient( + 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.set_mute( + securitycenter_service.SetMuteRequest(), + name="name_value", + mute=finding.Finding.Mute.MUTED, + ) + + +@pytest.mark.asyncio +async def test_set_mute_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_mute), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_mute( + name="name_value", + mute=finding.Finding.Mute.MUTED, + ) + + # 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].mute + mock_val = finding.Finding.Mute.MUTED + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_set_mute_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_mute( + securitycenter_service.SetMuteRequest(), + name="name_value", + mute=finding.Finding.Mute.MUTED, + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async( + transport: str = "grpc_asyncio", + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = SecurityCenterAsyncClient( + 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.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = SecurityCenterClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + + request.resource = "resource_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + client.test_iam_permissions(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", + "resource=resource_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + + request.resource = "resource_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + await client.test_iam_permissions(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", + "resource=resource_value", + ) in kw["metadata"] + + +def test_test_iam_permissions_from_dict_foreign(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource="resource_value", + permissions=["permissions_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].resource + mock_val = "resource_value" + assert arg == mock_val + arg = args[0].permissions + mock_val = ["permissions_value"] + assert arg == mock_val + + +def test_test_iam_permissions_flattened_error(): + client = SecurityCenterClient( + 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.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource="resource_value", + permissions=["permissions_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].resource + mock_val = "resource_value" + assert arg == mock_val + arg = args[0].permissions + mock_val = ["permissions_value"] + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.UpdateBigQueryExportRequest, + dict, + ], +) +def test_update_big_query_export(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_big_query_export), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport( + name="name_value", + description="description_value", + filter="filter_value", + dataset="dataset_value", + most_recent_editor="most_recent_editor_value", + principal="principal_value", + ) + response = client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.dataset == "dataset_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.principal == "principal_value" + + +def test_update_big_query_export_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), "__call__" + ) as call: + client.update_big_query_export() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() + + +@pytest.mark.asyncio +async def test_update_big_query_export_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.UpdateBigQueryExportRequest, +): + client = SecurityCenterAsyncClient( + 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_big_query_export), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigquery_export.BigQueryExport( + name="name_value", + description="description_value", + filter="filter_value", + dataset="dataset_value", + most_recent_editor="most_recent_editor_value", + principal="principal_value", + ) + ) + response = await client.update_big_query_export(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateBigQueryExportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.dataset == "dataset_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.principal == "principal_value" + + +@pytest.mark.asyncio +async def test_update_big_query_export_async_from_dict(): + await test_update_big_query_export_async(request_type=dict) + + +def test_update_big_query_export_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.UpdateBigQueryExportRequest() + + request.big_query_export.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), "__call__" + ) as call: + call.return_value = bigquery_export.BigQueryExport() + client.update_big_query_export(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", + "big_query_export.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_big_query_export_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateBigQueryExportRequest() + + request.big_query_export.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigquery_export.BigQueryExport() + ) + await client.update_big_query_export(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", + "big_query_export.name=name_value", + ) in kw["metadata"] + + +def test_update_big_query_export_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_big_query_export( + big_query_export=bigquery_export.BigQueryExport(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].big_query_export + mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error(): + client = SecurityCenterClient( + 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_big_query_export( + securitycenter_service.UpdateBigQueryExportRequest(), + big_query_export=bigquery_export.BigQueryExport(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_big_query_export_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_export), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bigquery_export.BigQueryExport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bigquery_export.BigQueryExport() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_big_query_export( + big_query_export=bigquery_export.BigQueryExport(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].big_query_export + mock_val = bigquery_export.BigQueryExport(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_big_query_export_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_big_query_export( + securitycenter_service.UpdateBigQueryExportRequest(), + big_query_export=bigquery_export.BigQueryExport(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.UpdateExternalSystemRequest, + dict, + ], +) +def test_update_external_system(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_external_system), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_external_system.ExternalSystem( + name="name_value", + assignees=["assignees_value"], + external_uid="external_uid_value", + status="status_value", + case_uri="case_uri_value", + case_priority="case_priority_value", + ) + response = client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateExternalSystemRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_external_system.ExternalSystem) + assert response.name == "name_value" + assert response.assignees == ["assignees_value"] + assert response.external_uid == "external_uid_value" + assert response.status == "status_value" + assert response.case_uri == "case_uri_value" + assert response.case_priority == "case_priority_value" + + +def test_update_external_system_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), "__call__" + ) as call: + client.update_external_system() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateExternalSystemRequest() + + +@pytest.mark.asyncio +async def test_update_external_system_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.UpdateExternalSystemRequest, +): + client = SecurityCenterAsyncClient( + 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_external_system), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_external_system.ExternalSystem( + name="name_value", + assignees=["assignees_value"], + external_uid="external_uid_value", + status="status_value", + case_uri="case_uri_value", + case_priority="case_priority_value", + ) + ) + response = await client.update_external_system(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateExternalSystemRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_external_system.ExternalSystem) + assert response.name == "name_value" + assert response.assignees == ["assignees_value"] + assert response.external_uid == "external_uid_value" + assert response.status == "status_value" + assert response.case_uri == "case_uri_value" + assert response.case_priority == "case_priority_value" + + +@pytest.mark.asyncio +async def test_update_external_system_async_from_dict(): + await test_update_external_system_async(request_type=dict) + + +def test_update_external_system_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.UpdateExternalSystemRequest() + + request.external_system.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), "__call__" + ) as call: + call.return_value = gcs_external_system.ExternalSystem() + client.update_external_system(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", + "external_system.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_external_system_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateExternalSystemRequest() + + request.external_system.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_external_system.ExternalSystem() + ) + await client.update_external_system(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", + "external_system.name=name_value", + ) in kw["metadata"] + + +def test_update_external_system_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_external_system.ExternalSystem() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_external_system( + external_system=gcs_external_system.ExternalSystem(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].external_system + mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error(): + client = SecurityCenterClient( + 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_external_system( + securitycenter_service.UpdateExternalSystemRequest(), + external_system=gcs_external_system.ExternalSystem(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_external_system_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_external_system), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_external_system.ExternalSystem() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_external_system.ExternalSystem() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_external_system( + external_system=gcs_external_system.ExternalSystem(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].external_system + mock_val = gcs_external_system.ExternalSystem(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_external_system_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_external_system( + securitycenter_service.UpdateExternalSystemRequest(), + external_system=gcs_external_system.ExternalSystem(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.UpdateFindingRequest, + dict, + ], +) +def test_update_finding(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_finding), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name="name_value", + canonical_name="canonical_name_value", + parent="parent_value", + resource_name="resource_name_value", + state=gcs_finding.Finding.State.ACTIVE, + category="category_value", + external_uri="external_uri_value", + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator="mute_initiator_value", + parent_display_name="parent_display_name_value", + description="description_value", + next_steps="next_steps_value", + module_name="module_name_value", + ) + response = client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" + assert response.parent == "parent_value" + assert response.resource_name == "resource_name_value" + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == "category_value" + assert response.external_uri == "external_uri_value" + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == "mute_initiator_value" + assert response.parent_display_name == "parent_display_name_value" + assert response.description == "description_value" + assert response.next_steps == "next_steps_value" + assert response.module_name == "module_name_value" + + +def test_update_finding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_finding), "__call__") as call: + client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + +@pytest.mark.asyncio +async def test_update_finding_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.UpdateFindingRequest, +): + client = SecurityCenterAsyncClient( + 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_finding), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_finding.Finding( + name="name_value", + canonical_name="canonical_name_value", + parent="parent_value", + resource_name="resource_name_value", + state=gcs_finding.Finding.State.ACTIVE, + category="category_value", + external_uri="external_uri_value", + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator="mute_initiator_value", + parent_display_name="parent_display_name_value", + description="description_value", + next_steps="next_steps_value", + module_name="module_name_value", + ) + ) + response = await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" + assert response.parent == "parent_value" + assert response.resource_name == "resource_name_value" + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == "category_value" + assert response.external_uri == "external_uri_value" + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == "mute_initiator_value" + assert response.parent_display_name == "parent_display_name_value" + assert response.description == "description_value" + assert response.next_steps == "next_steps_value" + assert response.module_name == "module_name_value" + + +@pytest.mark.asyncio +async def test_update_finding_async_from_dict(): + await test_update_finding_async(request_type=dict) + + +def test_update_finding_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.UpdateFindingRequest() + + request.finding.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_finding), "__call__") as call: + call.return_value = gcs_finding.Finding() + client.update_finding(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", + "finding.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateFindingRequest() + + request.finding.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_finding), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.update_finding(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", + "finding.name=name_value", + ) in kw["metadata"] + + +def test_update_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_finding), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_finding( + finding=gcs_finding.Finding(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].finding + mock_val = gcs_finding.Finding(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_finding_flattened_error(): + client = SecurityCenterClient( + 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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_finding), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_finding( + finding=gcs_finding.Finding(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].finding + mock_val = gcs_finding.Finding(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_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.UpdateMuteConfigRequest, + dict, + ], +) +def test_update_mute_config(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_mute_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig( + name="name_value", + description="description_value", + filter="filter_value", + most_recent_editor="most_recent_editor_value", + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + response = client.update_mute_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] == securitycenter_service.UpdateMuteConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +def test_update_mute_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), "__call__" + ) as call: + client.update_mute_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateMuteConfigRequest() + + +@pytest.mark.asyncio +async def test_update_mute_config_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.UpdateMuteConfigRequest, +): + client = SecurityCenterAsyncClient( + 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_mute_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_mute_config.MuteConfig( + name="name_value", + description="description_value", + filter="filter_value", + most_recent_editor="most_recent_editor_value", + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + ) + response = await client.update_mute_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateMuteConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +@pytest.mark.asyncio +async def test_update_mute_config_async_from_dict(): + await test_update_mute_config_async(request_type=dict) + + +def test_update_mute_config_routing_parameters(): + client = SecurityCenterClient( + 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 = securitycenter_service.UpdateMuteConfigRequest( + **{ + "mute_config": { + "name": "projects/sample1/locations/sample2/muteConfigs/sample3" + } + } + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), "__call__" + ) as call: + call.return_value = gcs_mute_config.MuteConfig() + client.update_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw["metadata"] + # 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 = securitycenter_service.UpdateMuteConfigRequest( + **{ + "mute_config": { + "name": "organizations/sample1/locations/sample2/muteConfigs/sample3" + } + } + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), "__call__" + ) as call: + call.return_value = gcs_mute_config.MuteConfig() + client.update_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw["metadata"] + # 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 = securitycenter_service.UpdateMuteConfigRequest( + **{ + "mute_config": { + "name": "folders/sample1/locations/sample2/muteConfigs/sample3" + } + } + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), "__call__" + ) as call: + call.return_value = gcs_mute_config.MuteConfig() + client.update_mute_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 + + _, _, kw = call.mock_calls[0] + # This test doesn't assert anything useful. + assert kw["metadata"] + + +def test_update_mute_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_mute_config( + mute_config=gcs_mute_config.MuteConfig(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].mute_config + mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error(): + client = SecurityCenterClient( + 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_mute_config( + securitycenter_service.UpdateMuteConfigRequest(), + mute_config=gcs_mute_config.MuteConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_mute_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_mute_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_mute_config.MuteConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_mute_config.MuteConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_mute_config( + mute_config=gcs_mute_config.MuteConfig(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].mute_config + mock_val = gcs_mute_config.MuteConfig(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_mute_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_mute_config( + securitycenter_service.UpdateMuteConfigRequest(), + mute_config=gcs_mute_config.MuteConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.UpdateNotificationConfigRequest, + dict, + ], +) +def test_update_notification_config(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_notification_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name="name_value", + description="description_value", + pubsub_topic="pubsub_topic_value", + service_account="service_account_value", + ) + response = client.update_notification_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] == securitycenter_service.UpdateNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.pubsub_topic == "pubsub_topic_value" + assert response.service_account == "service_account_value" + + +def test_update_notification_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), "__call__" + ) as call: + client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + + +@pytest.mark.asyncio +async def test_update_notification_config_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.UpdateNotificationConfigRequest, +): + client = SecurityCenterAsyncClient( + 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_notification_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_notification_config.NotificationConfig( + name="name_value", + description="description_value", + pubsub_topic="pubsub_topic_value", + service_account="service_account_value", + ) + ) + response = await client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.pubsub_topic == "pubsub_topic_value" + assert response.service_account == "service_account_value" + + +@pytest.mark.asyncio +async def test_update_notification_config_async_from_dict(): + await test_update_notification_config_async(request_type=dict) + + +def test_update_notification_config_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), "__call__" + ) as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.update_notification_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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "notification_config.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_notification_config.NotificationConfig() + ) + await client.update_notification_config(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", + "notification_config.name=name_value", + ) in kw["metadata"] + + +def test_update_notification_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig( + 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].notification_config + mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error(): + client = SecurityCenterClient( + 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_notification_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_notification_config.NotificationConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig( + 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].notification_config + mock_val = gcs_notification_config.NotificationConfig(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_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_notification_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.UpdateResourceValueConfigRequest, + dict, + ], +) +def test_update_resource_value_config(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_resource_value_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_resource_value_config.ResourceValueConfig( + name="name_value", + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=["tag_values_value"], + resource_type="resource_type_value", + scope="scope_value", + description="description_value", + ) + response = client.update_resource_value_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] == securitycenter_service.UpdateResourceValueConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) + assert response.name == "name_value" + assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH + assert response.tag_values == ["tag_values_value"] + assert response.resource_type == "resource_type_value" + assert response.scope == "scope_value" + assert response.description == "description_value" + + +def test_update_resource_value_config_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), "__call__" + ) as call: + client.update_resource_value_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() + + +@pytest.mark.asyncio +async def test_update_resource_value_config_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.UpdateResourceValueConfigRequest, +): + client = SecurityCenterAsyncClient( + 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_resource_value_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_resource_value_config.ResourceValueConfig( + name="name_value", + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=["tag_values_value"], + resource_type="resource_type_value", + scope="scope_value", + description="description_value", + ) + ) + response = await client.update_resource_value_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateResourceValueConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) + assert response.name == "name_value" + assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH + assert response.tag_values == ["tag_values_value"] + assert response.resource_type == "resource_type_value" + assert response.scope == "scope_value" + assert response.description == "description_value" + + +@pytest.mark.asyncio +async def test_update_resource_value_config_async_from_dict(): + await test_update_resource_value_config_async(request_type=dict) + + +def test_update_resource_value_config_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.UpdateResourceValueConfigRequest() + + request.resource_value_config.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), "__call__" + ) as call: + call.return_value = gcs_resource_value_config.ResourceValueConfig() + client.update_resource_value_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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource_value_config.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_resource_value_config_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateResourceValueConfigRequest() + + request.resource_value_config.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_resource_value_config.ResourceValueConfig() + ) + await client.update_resource_value_config(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", + "resource_value_config.name=name_value", + ) in kw["metadata"] + + +def test_update_resource_value_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_resource_value_config.ResourceValueConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_resource_value_config( + resource_value_config=gcs_resource_value_config.ResourceValueConfig( + 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].resource_value_config + mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error(): + client = SecurityCenterClient( + 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_resource_value_config( + securitycenter_service.UpdateResourceValueConfigRequest(), + resource_value_config=gcs_resource_value_config.ResourceValueConfig( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_resource_value_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_resource_value_config), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_resource_value_config.ResourceValueConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_resource_value_config.ResourceValueConfig() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_resource_value_config( + resource_value_config=gcs_resource_value_config.ResourceValueConfig( + 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].resource_value_config + mock_val = gcs_resource_value_config.ResourceValueConfig(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_resource_value_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_resource_value_config( + securitycenter_service.UpdateResourceValueConfigRequest(), + resource_value_config=gcs_resource_value_config.ResourceValueConfig( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, + ], +) +def test_update_security_marks(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_security_marks), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks( + name="name_value", + canonical_name="canonical_name_value", + ) + response = client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" + + +def test_update_security_marks_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), "__call__" + ) as call: + client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + +@pytest.mark.asyncio +async def test_update_security_marks_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.UpdateSecurityMarksRequest, +): + client = SecurityCenterAsyncClient( + 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_security_marks), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_security_marks.SecurityMarks( + name="name_value", + canonical_name="canonical_name_value", + ) + ) + response = await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" + + +@pytest.mark.asyncio +async def test_update_security_marks_async_from_dict(): + await test_update_security_marks_async(request_type=dict) + + +def test_update_security_marks_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), "__call__" + ) as call: + call.return_value = gcs_security_marks.SecurityMarks() + client.update_security_marks(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", + "security_marks.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_security_marks_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_security_marks.SecurityMarks() + ) + await client.update_security_marks(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", + "security_marks.name=name_value", + ) in kw["metadata"] + + +def test_update_security_marks_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(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].security_marks + mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error(): + client = SecurityCenterClient( + 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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_security_marks.SecurityMarks() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(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].security_marks + mock_val = gcs_security_marks.SecurityMarks(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_security_marks_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.UpdateSourceRequest, + dict, + ], +) +def test_update_source(request_type, transport: str = "grpc"): + client = SecurityCenterClient( + 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_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name="name_value", + display_name="display_name_value", + description="description_value", + canonical_name="canonical_name_value", + ) + response = client.update_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] == securitycenter_service.UpdateSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" + + +def test_update_source_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_source), "__call__") as call: + client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + +@pytest.mark.asyncio +async def test_update_source_async( + transport: str = "grpc_asyncio", + request_type=securitycenter_service.UpdateSourceRequest, +): + client = SecurityCenterAsyncClient( + 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_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_source.Source( + name="name_value", + display_name="display_name_value", + description="description_value", + canonical_name="canonical_name_value", + ) + ) + response = await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" + + +@pytest.mark.asyncio +async def test_update_source_async_from_dict(): + await test_update_source_async(request_type=dict) + + +def test_update_source_field_headers(): + client = SecurityCenterClient( + 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 = securitycenter_service.UpdateSourceRequest() + + request.source.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_source), "__call__") as call: + call.return_value = gcs_source.Source() + client.update_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", + "source.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_source_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = securitycenter_service.UpdateSourceRequest() + + request.source.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_source), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.update_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", + "source.name=name_value", + ) in kw["metadata"] + + +def test_update_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_source( + source=gcs_source.Source(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].source + mock_val = gcs_source.Source(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_source_flattened_error(): + client = SecurityCenterClient( + 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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_source( + source=gcs_source.Source(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].source + mock_val = gcs_source.Source(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_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.BatchCreateResourceValueConfigsRequest, + dict, + ], +) +def test_batch_create_resource_value_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ( + securitycenter_service.BatchCreateResourceValueConfigsResponse.pb( + 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_create_resource_value_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, securitycenter_service.BatchCreateResourceValueConfigsResponse + ) + + +def test_batch_create_resource_value_configs_rest_required_fields( + request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_create_resource_value_configs._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_resource_value_configs._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.BatchCreateResourceValueConfigsResponse() + # 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 = ( + securitycenter_service.BatchCreateResourceValueConfigsResponse.pb( + 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_create_resource_value_configs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_batch_create_resource_value_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.batch_create_resource_value_configs._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "requests", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_resource_value_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, + "post_batch_create_resource_value_configs", + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, + "pre_batch_create_resource_value_configs", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.BatchCreateResourceValueConfigsRequest.pb( + securitycenter_service.BatchCreateResourceValueConfigsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + securitycenter_service.BatchCreateResourceValueConfigsResponse.to_json( + securitycenter_service.BatchCreateResourceValueConfigsResponse() + ) + ) + + request = securitycenter_service.BatchCreateResourceValueConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + securitycenter_service.BatchCreateResourceValueConfigsResponse() + ) + + client.batch_create_resource_value_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_create_resource_value_configs_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.BatchCreateResourceValueConfigsRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_create_resource_value_configs(request) + + +def test_batch_create_resource_value_configs_rest_flattened(): + client = SecurityCenterClient( + 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 = securitycenter_service.BatchCreateResourceValueConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + requests=[ + securitycenter_service.CreateResourceValueConfigRequest( + 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 = ( + securitycenter_service.BatchCreateResourceValueConfigsResponse.pb( + 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.batch_create_resource_value_configs(**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/v2/{parent=organizations/*}/resourceValueConfigs:batchCreate" + % client.transport._host, + args[1], + ) + + +def test_batch_create_resource_value_configs_rest_flattened_error( + transport: str = "rest", +): + client = SecurityCenterClient( + 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.batch_create_resource_value_configs( + securitycenter_service.BatchCreateResourceValueConfigsRequest(), + parent="parent_value", + requests=[ + securitycenter_service.CreateResourceValueConfigRequest( + parent="parent_value" + ) + ], + ) + + +def test_batch_create_resource_value_configs_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.BulkMuteFindingsRequest, + dict, + ], +) +def test_bulk_mute_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # 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 + response = client.bulk_mute_findings(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_bulk_mute_findings_rest_required_fields( + request_type=securitycenter_service.BulkMuteFindingsRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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() + ).bulk_mute_findings._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() + ).bulk_mute_findings._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 = SecurityCenterClient( + 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.bulk_mute_findings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_bulk_mute_findings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.bulk_mute_findings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_bulk_mute_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_bulk_mute_findings" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_bulk_mute_findings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.BulkMuteFindingsRequest.pb( + securitycenter_service.BulkMuteFindingsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = securitycenter_service.BulkMuteFindingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.bulk_mute_findings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_bulk_mute_findings_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.BulkMuteFindingsRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.bulk_mute_findings(request) + + +def test_bulk_mute_findings_rest_flattened(): + client = SecurityCenterClient( + 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": "organizations/sample1"} + + # 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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.bulk_mute_findings(**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/v2/{parent=organizations/*}/findings:bulkMute" % client.transport._host, + args[1], + ) + + +def test_bulk_mute_findings_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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.bulk_mute_findings( + securitycenter_service.BulkMuteFindingsRequest(), + parent="parent_value", + ) + + +def test_bulk_mute_findings_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.CreateBigQueryExportRequest, + dict, + ], +) +def test_create_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/locations/sample2"} + request_init["big_query_export"] = { + "name": "name_value", + "description": "description_value", + "filter": "filter_value", + "dataset": "dataset_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "most_recent_editor": "most_recent_editor_value", + "principal": "principal_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 = securitycenter_service.CreateBigQueryExportRequest.meta.fields[ + "big_query_export" + ] + + 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["big_query_export"].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["big_query_export"][field])): + del request_init["big_query_export"][field][i][subfield] + else: + del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( + name="name_value", + description="description_value", + filter="filter_value", + dataset="dataset_value", + most_recent_editor="most_recent_editor_value", + principal="principal_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 = bigquery_export.BigQueryExport.pb(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.create_big_query_export(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.dataset == "dataset_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.principal == "principal_value" + + +def test_create_big_query_export_rest_required_fields( + request_type=securitycenter_service.CreateBigQueryExportRequest, +): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["big_query_export_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 "bigQueryExportId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_big_query_export._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "bigQueryExportId" in jsonified_request + assert jsonified_request["bigQueryExportId"] == request_init["big_query_export_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["bigQueryExportId"] = "big_query_export_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_big_query_export._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("big_query_export_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 "bigQueryExportId" in jsonified_request + assert jsonified_request["bigQueryExportId"] == "big_query_export_id_value" + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + # 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 = bigquery_export.BigQueryExport.pb(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.create_big_query_export(request) + + expected_params = [ + ( + "bigQueryExportId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("bigQueryExportId",)) + & set( + ( + "parent", + "bigQueryExport", + "bigQueryExportId", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_create_big_query_export" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_create_big_query_export" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateBigQueryExportRequest.pb( + securitycenter_service.CreateBigQueryExportRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = bigquery_export.BigQueryExport.to_json( + bigquery_export.BigQueryExport() + ) + + request = securitycenter_service.CreateBigQueryExportRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigquery_export.BigQueryExport() + + client.create_big_query_export( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_big_query_export_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.CreateBigQueryExportRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_big_query_export(request) + + +def test_create_big_query_export_rest_flattened(): + client = SecurityCenterClient( + 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 = bigquery_export.BigQueryExport() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + big_query_export=bigquery_export.BigQueryExport(name="name_value"), + big_query_export_id="big_query_export_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 = bigquery_export.BigQueryExport.pb(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.create_big_query_export(**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/v2/{parent=organizations/*/locations/*}/bigQueryExports" + % client.transport._host, + args[1], + ) + + +def test_create_big_query_export_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_big_query_export( + securitycenter_service.CreateBigQueryExportRequest(), + parent="parent_value", + big_query_export=bigquery_export.BigQueryExport(name="name_value"), + big_query_export_id="big_query_export_id_value", + ) + + +def test_create_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.CreateFindingRequest, + dict, + ], +) +def test_create_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/sources/sample2/locations/sample3"} + request_init["finding"] = { + "name": "name_value", + "canonical_name": "canonical_name_value", + "parent": "parent_value", + "resource_name": "resource_name_value", + "state": 1, + "category": "category_value", + "external_uri": "external_uri_value", + "source_properties": {}, + "security_marks": { + "name": "name_value", + "marks": {}, + "canonical_name": "canonical_name_value", + }, + "event_time": {"seconds": 751, "nanos": 543}, + "create_time": {}, + "severity": 1, + "mute": 1, + "finding_class": 1, + "indicator": { + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "domains": ["domains_value1", "domains_value2"], + "signatures": [ + { + "memory_hash_signature": { + "binary_family": "binary_family_value", + "detections": [ + {"binary": "binary_value", "percent_pages_matched": 0.2197} + ], + }, + "yara_rule_signature": {"yara_rule": "yara_rule_value"}, + "signature_type": 1, + } + ], + "uris": ["uris_value1", "uris_value2"], + }, + "vulnerability": { + "cve": { + "id": "id_value", + "references": [{"source": "source_value", "uri": "uri_value"}], + "cvssv3": { + "base_score": 0.1046, + "attack_vector": 1, + "attack_complexity": 1, + "privileges_required": 1, + "user_interaction": 1, + "scope": 1, + "confidentiality_impact": 1, + "integrity_impact": 1, + "availability_impact": 1, + }, + "upstream_fix_available": True, + "impact": 1, + "exploitation_activity": 1, + "observed_in_the_wild": True, + "zero_day": True, + }, + "offending_package": { + "package_name": "package_name_value", + "cpe_uri": "cpe_uri_value", + "package_type": "package_type_value", + "package_version": "package_version_value", + }, + "fixed_package": {}, + "security_bulletin": { + "bulletin_id": "bulletin_id_value", + "submission_time": {}, + "suggested_upgrade_version": "suggested_upgrade_version_value", + }, + }, + "mute_update_time": {}, + "external_systems": {}, + "mitre_attack": { + "primary_tactic": 1, + "primary_techniques": [49], + "additional_tactics": [1], + "additional_techniques": [49], + "version": "version_value", + }, + "access": { + "principal_email": "principal_email_value", + "caller_ip": "caller_ip_value", + "caller_ip_geo": {"region_code": "region_code_value"}, + "user_agent_family": "user_agent_family_value", + "user_agent": "user_agent_value", + "service_name": "service_name_value", + "method_name": "method_name_value", + "principal_subject": "principal_subject_value", + "service_account_key_name": "service_account_key_name_value", + "service_account_delegation_info": [ + { + "principal_email": "principal_email_value", + "principal_subject": "principal_subject_value", + } + ], + "user_name": "user_name_value", + }, + "connections": [ + { + "destination_ip": "destination_ip_value", + "destination_port": 1734, + "source_ip": "source_ip_value", + "source_port": 1205, + "protocol": 1, + } + ], + "mute_initiator": "mute_initiator_value", + "processes": [ + { + "name": "name_value", + "binary": { + "path": "path_value", + "size": 443, + "sha256": "sha256_value", + "hashed_size": 1159, + "partially_hashed": True, + "contents": "contents_value", + "disk_path": { + "partition_uuid": "partition_uuid_value", + "relative_path": "relative_path_value", + }, + }, + "libraries": {}, + "script": {}, + "args": ["args_value1", "args_value2"], + "arguments_truncated": True, + "env_variables": [{"name": "name_value", "val": "val_value"}], + "env_variables_truncated": True, + "pid": 317, + "parent_pid": 1062, + } + ], + "contacts": {}, + "compliances": [ + { + "standard": "standard_value", + "version": "version_value", + "ids": ["ids_value1", "ids_value2"], + } + ], + "parent_display_name": "parent_display_name_value", + "description": "description_value", + "exfiltration": { + "sources": [ + { + "name": "name_value", + "components": ["components_value1", "components_value2"], + } + ], + "targets": {}, + "total_exfiltrated_bytes": 2469, + }, + "iam_bindings": [{"action": 1, "role": "role_value", "member": "member_value"}], + "next_steps": "next_steps_value", + "module_name": "module_name_value", + "containers": [ + { + "name": "name_value", + "uri": "uri_value", + "image_id": "image_id_value", + "labels": [{"name": "name_value", "value": "value_value"}], + "create_time": {}, + } + ], + "kubernetes": { + "pods": [ + {"ns": "ns_value", "name": "name_value", "labels": {}, "containers": {}} + ], + "nodes": [{"name": "name_value"}], + "node_pools": [{"name": "name_value", "nodes": {}}], + "roles": [{"kind": 1, "ns": "ns_value", "name": "name_value"}], + "bindings": [ + { + "ns": "ns_value", + "name": "name_value", + "role": {}, + "subjects": [{"kind": 1, "ns": "ns_value", "name": "name_value"}], + } + ], + "access_reviews": [ + { + "group": "group_value", + "ns": "ns_value", + "name": "name_value", + "resource": "resource_value", + "subresource": "subresource_value", + "verb": "verb_value", + "version": "version_value", + } + ], + "objects": [ + { + "group": "group_value", + "kind": "kind_value", + "ns": "ns_value", + "name": "name_value", + "containers": {}, + } + ], + }, + "database": { + "name": "name_value", + "display_name": "display_name_value", + "user_name": "user_name_value", + "query": "query_value", + "grantees": ["grantees_value1", "grantees_value2"], + "version": "version_value", + }, + "attack_exposure": { + "score": 0.54, + "latest_calculation_time": {}, + "attack_exposure_result": "attack_exposure_result_value", + "state": 1, + "exposed_high_value_resources_count": 3637, + "exposed_medium_value_resources_count": 3862, + "exposed_low_value_resources_count": 3559, + }, + "files": {}, + "cloud_dlp_inspection": { + "inspect_job": "inspect_job_value", + "info_type": "info_type_value", + "info_type_count": 1621, + "full_scan": True, + }, + "cloud_dlp_data_profile": { + "data_profile": "data_profile_value", + "parent_type": 1, + }, + "kernel_rootkit": { + "name": "name_value", + "unexpected_code_modification": True, + "unexpected_read_only_data_modification": True, + "unexpected_ftrace_handler": True, + "unexpected_kprobe_handler": True, + "unexpected_kernel_code_pages": True, + "unexpected_system_call_handler": True, + "unexpected_interrupt_handler": True, + "unexpected_processes_in_runqueue": True, + }, + "org_policies": [{"name": "name_value"}], + "application": {"base_uri": "base_uri_value", "full_uri": "full_uri_value"}, + "backup_disaster_recovery": { + "backup_template": "backup_template_value", + "policies": ["policies_value1", "policies_value2"], + "host": "host_value", + "applications": ["applications_value1", "applications_value2"], + "storage_pool": "storage_pool_value", + "policy_options": ["policy_options_value1", "policy_options_value2"], + "profile": "profile_value", + "appliance": "appliance_value", + "backup_type": "backup_type_value", + "backup_create_time": {}, + }, + "security_posture": { + "name": "name_value", + "revision_id": "revision_id_value", + "posture_deployment_resource": "posture_deployment_resource_value", + "posture_deployment": "posture_deployment_value", + "changed_policy": "changed_policy_value", + "policy_set": "policy_set_value", + "policy": "policy_value", + "policy_drift_details": [ + { + "field": "field_value", + "expected_value": "expected_value_value", + "detected_value": "detected_value_value", + } + ], + }, + "log_entries": [ + { + "cloud_logging_entry": { + "insert_id": "insert_id_value", + "log_id": "log_id_value", + "resource_container": "resource_container_value", + "timestamp": {}, + } + } + ], + "load_balancers": [{"name": "name_value"}], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = securitycenter_service.CreateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name="name_value", + canonical_name="canonical_name_value", + parent="parent_value", + resource_name="resource_name_value", + state=gcs_finding.Finding.State.ACTIVE, + category="category_value", + external_uri="external_uri_value", + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator="mute_initiator_value", + parent_display_name="parent_display_name_value", + description="description_value", + next_steps="next_steps_value", + module_name="module_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 = gcs_finding.Finding.pb(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.create_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" + assert response.parent == "parent_value" + assert response.resource_name == "resource_name_value" + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == "category_value" + assert response.external_uri == "external_uri_value" + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == "mute_initiator_value" + assert response.parent_display_name == "parent_display_name_value" + assert response.description == "description_value" + assert response.next_steps == "next_steps_value" + assert response.module_name == "module_name_value" + + +def test_create_finding_rest_required_fields( + request_type=securitycenter_service.CreateFindingRequest, +): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["finding_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 "findingId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_finding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "findingId" in jsonified_request + assert jsonified_request["findingId"] == request_init["finding_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["findingId"] = "finding_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_finding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("finding_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 "findingId" in jsonified_request + assert jsonified_request["findingId"] == "finding_id_value" + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + # 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 = gcs_finding.Finding.pb(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.create_finding(request) + + expected_params = [ + ( + "findingId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_finding._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("findingId",)) + & set( + ( + "parent", + "findingId", + "finding", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_create_finding" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_create_finding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateFindingRequest.pb( + securitycenter_service.CreateFindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.CreateFindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.create_finding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_finding_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.CreateFindingRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/sources/sample2/locations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_finding(request) + + +def test_create_finding_rest_flattened(): + client = SecurityCenterClient( + 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 = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "organizations/sample1/sources/sample2/locations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + finding=gcs_finding.Finding(name="name_value"), + finding_id="finding_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 = gcs_finding.Finding.pb(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.create_finding(**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/v2/{parent=organizations/*/sources/*/locations/*}/findings" + % client.transport._host, + args[1], + ) + + +def test_create_finding_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_finding( + securitycenter_service.CreateFindingRequest(), + parent="parent_value", + finding=gcs_finding.Finding(name="name_value"), + finding_id="finding_id_value", + ) + + +def test_create_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.CreateMuteConfigRequest, + dict, + ], +) +def test_create_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/locations/sample2"} + request_init["mute_config"] = { + "name": "name_value", + "description": "description_value", + "filter": "filter_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "most_recent_editor": "most_recent_editor_value", + "type_": 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 = securitycenter_service.CreateMuteConfigRequest.meta.fields[ + "mute_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["mute_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["mute_config"][field])): + del request_init["mute_config"][field][i][subfield] + else: + del request_init["mute_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 = gcs_mute_config.MuteConfig( + name="name_value", + description="description_value", + filter="filter_value", + most_recent_editor="most_recent_editor_value", + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_mute_config.MuteConfig.pb(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.create_mute_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +def test_create_mute_config_rest_required_fields( + request_type=securitycenter_service.CreateMuteConfigRequest, +): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["mute_config_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 "muteConfigId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_mute_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "muteConfigId" in jsonified_request + assert jsonified_request["muteConfigId"] == request_init["mute_config_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["muteConfigId"] = "mute_config_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_mute_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("mute_config_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 "muteConfigId" in jsonified_request + assert jsonified_request["muteConfigId"] == "mute_config_id_value" + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + # 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 = gcs_mute_config.MuteConfig.pb(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.create_mute_config(request) + + expected_params = [ + ( + "muteConfigId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("muteConfigId",)) + & set( + ( + "parent", + "muteConfig", + "muteConfigId", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_create_mute_config" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_create_mute_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateMuteConfigRequest.pb( + securitycenter_service.CreateMuteConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_mute_config.MuteConfig.to_json( + gcs_mute_config.MuteConfig() + ) + + request = securitycenter_service.CreateMuteConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_mute_config.MuteConfig() + + client.create_mute_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_mute_config_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.CreateMuteConfigRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_mute_config(request) + + +def test_create_mute_config_rest_flattened(): + client = SecurityCenterClient( + 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 = gcs_mute_config.MuteConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + mute_config=gcs_mute_config.MuteConfig(name="name_value"), + mute_config_id="mute_config_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 = gcs_mute_config.MuteConfig.pb(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.create_mute_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/v2/{parent=organizations/*/locations/*}/muteConfigs" + % client.transport._host, + args[1], + ) + + +def test_create_mute_config_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_mute_config( + securitycenter_service.CreateMuteConfigRequest(), + parent="parent_value", + mute_config=gcs_mute_config.MuteConfig(name="name_value"), + mute_config_id="mute_config_id_value", + ) + + +def test_create_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.CreateNotificationConfigRequest, + dict, + ], +) +def test_create_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/locations/sample2"} + request_init["notification_config"] = { + "name": "name_value", + "description": "description_value", + "pubsub_topic": "pubsub_topic_value", + "service_account": "service_account_value", + "streaming_config": {"filter": "filter_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 = securitycenter_service.CreateNotificationConfigRequest.meta.fields[ + "notification_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["notification_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["notification_config"][field])): + del request_init["notification_config"][field][i][subfield] + else: + del request_init["notification_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 = gcs_notification_config.NotificationConfig( + name="name_value", + description="description_value", + pubsub_topic="pubsub_topic_value", + service_account="service_account_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 = gcs_notification_config.NotificationConfig.pb(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.create_notification_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.pubsub_topic == "pubsub_topic_value" + assert response.service_account == "service_account_value" + + +def test_create_notification_config_rest_required_fields( + request_type=securitycenter_service.CreateNotificationConfigRequest, +): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["config_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 "configId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_notification_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "configId" in jsonified_request + assert jsonified_request["configId"] == request_init["config_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["configId"] = "config_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_notification_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("config_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 "configId" in jsonified_request + assert jsonified_request["configId"] == "config_id_value" + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + # 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 = gcs_notification_config.NotificationConfig.pb(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.create_notification_config(request) + + expected_params = [ + ( + "configId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("configId",)) + & set( + ( + "parent", + "configId", + "notificationConfig", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_create_notification_config" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_create_notification_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateNotificationConfigRequest.pb( + securitycenter_service.CreateNotificationConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_notification_config.NotificationConfig.to_json( + gcs_notification_config.NotificationConfig() + ) + + request = securitycenter_service.CreateNotificationConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_notification_config.NotificationConfig() + + client.create_notification_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_notification_config_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.CreateNotificationConfigRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_notification_config(request) + + +def test_create_notification_config_rest_flattened(): + client = SecurityCenterClient( + 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 = gcs_notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + notification_config=gcs_notification_config.NotificationConfig( + name="name_value" + ), + config_id="config_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 = gcs_notification_config.NotificationConfig.pb(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.create_notification_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/v2/{parent=organizations/*/locations/*}/notificationConfigs" + % client.transport._host, + args[1], + ) + + +def test_create_notification_config_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_notification_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent="parent_value", + notification_config=gcs_notification_config.NotificationConfig( + name="name_value" + ), + config_id="config_id_value", + ) + + +def test_create_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.CreateSourceRequest, + dict, + ], +) +def test_create_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request_init["source"] = { + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "canonical_name": "canonical_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 = securitycenter_service.CreateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name="name_value", + display_name="display_name_value", + description="description_value", + canonical_name="canonical_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 = gcs_source.Source.pb(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.create_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" + + +def test_create_source_rest_required_fields( + request_type=securitycenter_service.CreateSourceRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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() + ).create_source._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() + ).create_source._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # 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 = gcs_source.Source.pb(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.create_source(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_source._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "source", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_create_source" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_create_source" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.CreateSourceRequest.pb( + securitycenter_service.CreateSourceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.CreateSourceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.create_source( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_source_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.CreateSourceRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_source(request) + + +def test_create_source_rest_flattened(): + client = SecurityCenterClient( + 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 = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + source=gcs_source.Source(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 = gcs_source.Source.pb(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.create_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/v2/{parent=organizations/*}/sources" % client.transport._host, args[1] + ) + + +def test_create_source_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_source( + securitycenter_service.CreateSourceRequest(), + parent="parent_value", + source=gcs_source.Source(name="name_value"), + ) + + +def test_create_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.DeleteBigQueryExportRequest, + dict, + ], +) +def test_delete_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/bigQueryExports/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_big_query_export(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_big_query_export_rest_required_fields( + request_type=securitycenter_service.DeleteBigQueryExportRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_big_query_export._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_big_query_export._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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 = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_big_query_export(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "pre_delete_big_query_export" + ) as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteBigQueryExportRequest.pb( + securitycenter_service.DeleteBigQueryExportRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteBigQueryExportRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_big_query_export( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_big_query_export_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.DeleteBigQueryExportRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/bigQueryExports/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_big_query_export(request) + + +def test_delete_big_query_export_rest_flattened(): + client = SecurityCenterClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/bigQueryExports/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 = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_big_query_export(**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/v2/{name=organizations/*/locations/*/bigQueryExports/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_big_query_export_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_big_query_export( + securitycenter_service.DeleteBigQueryExportRequest(), + name="name_value", + ) + + +def test_delete_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.DeleteMuteConfigRequest, + dict, + ], +) +def test_delete_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/muteConfigs/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_mute_config(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_mute_config_rest_required_fields( + request_type=securitycenter_service.DeleteMuteConfigRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_mute_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() + ).delete_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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 = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_mute_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "pre_delete_mute_config" + ) as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteMuteConfigRequest.pb( + securitycenter_service.DeleteMuteConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteMuteConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_mute_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_mute_config_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.DeleteMuteConfigRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/muteConfigs/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_mute_config(request) + + +def test_delete_mute_config_rest_flattened(): + client = SecurityCenterClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/muteConfigs/sample2"} + + # 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 = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_mute_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/v2/{name=organizations/*/muteConfigs/*}" % client.transport._host, + args[1], + ) + + +def test_delete_mute_config_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_mute_config( + securitycenter_service.DeleteMuteConfigRequest(), + name="name_value", + ) + + +def test_delete_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.DeleteNotificationConfigRequest, + dict, + ], +) +def test_delete_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/notificationConfigs/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_notification_config(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_notification_config_rest_required_fields( + request_type=securitycenter_service.DeleteNotificationConfigRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_notification_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() + ).delete_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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 = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_notification_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "pre_delete_notification_config" + ) as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteNotificationConfigRequest.pb( + securitycenter_service.DeleteNotificationConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteNotificationConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_notification_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_notification_config_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.DeleteNotificationConfigRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/notificationConfigs/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_notification_config(request) + + +def test_delete_notification_config_rest_flattened(): + client = SecurityCenterClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/notificationConfigs/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 = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_notification_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/v2/{name=organizations/*/locations/*/notificationConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_notification_config_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_notification_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name="name_value", + ) + + +def test_delete_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.DeleteResourceValueConfigRequest, + dict, + ], +) +def test_delete_resource_value_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/resourceValueConfigs/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_resource_value_config(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_resource_value_config_rest_required_fields( + request_type=securitycenter_service.DeleteResourceValueConfigRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_resource_value_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() + ).delete_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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 = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_resource_value_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_resource_value_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_resource_value_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_resource_value_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "pre_delete_resource_value_config" + ) as pre: + pre.assert_not_called() + pb_message = securitycenter_service.DeleteResourceValueConfigRequest.pb( + securitycenter_service.DeleteResourceValueConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = securitycenter_service.DeleteResourceValueConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_resource_value_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_resource_value_config_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.DeleteResourceValueConfigRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/resourceValueConfigs/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_resource_value_config(request) + + +def test_delete_resource_value_config_rest_flattened(): + client = SecurityCenterClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/resourceValueConfigs/sample2"} + + # 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 = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_resource_value_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/v2/{name=organizations/*/resourceValueConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_resource_value_config_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_resource_value_config( + securitycenter_service.DeleteResourceValueConfigRequest(), + name="name_value", + ) + + +def test_delete_resource_value_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.GetBigQueryExportRequest, + dict, + ], +) +def test_get_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/bigQueryExports/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 = bigquery_export.BigQueryExport( + name="name_value", + description="description_value", + filter="filter_value", + dataset="dataset_value", + most_recent_editor="most_recent_editor_value", + principal="principal_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 = bigquery_export.BigQueryExport.pb(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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.dataset == "dataset_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.principal == "principal_value" + + +def test_get_big_query_export_rest_required_fields( + request_type=securitycenter_service.GetBigQueryExportRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_big_query_export._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_big_query_export._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + # 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 = bigquery_export.BigQueryExport.pb(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_big_query_export(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_get_big_query_export" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_get_big_query_export" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetBigQueryExportRequest.pb( + securitycenter_service.GetBigQueryExportRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = bigquery_export.BigQueryExport.to_json( + bigquery_export.BigQueryExport() + ) + + request = securitycenter_service.GetBigQueryExportRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigquery_export.BigQueryExport() + + client.get_big_query_export( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_big_query_export_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.GetBigQueryExportRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/bigQueryExports/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_big_query_export(request) + + +def test_get_big_query_export_rest_flattened(): + client = SecurityCenterClient( + 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 = bigquery_export.BigQueryExport() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/bigQueryExports/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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**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/v2/{name=organizations/*/locations/*/bigQueryExports/*}" + % client.transport._host, + args[1], + ) + + +def test_get_big_query_export_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_big_query_export( + securitycenter_service.GetBigQueryExportRequest(), + name="name_value", + ) + + +def test_get_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.GetSimulationRequest, + dict, + ], +) +def test_get_simulation_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/simulations/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 = simulation.Simulation( + 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 = simulation.Simulation.pb(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_simulation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, simulation.Simulation) + assert response.name == "name_value" + + +def test_get_simulation_rest_required_fields( + request_type=securitycenter_service.GetSimulationRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_simulation._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_simulation._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = simulation.Simulation() + # 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 = simulation.Simulation.pb(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_simulation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_simulation_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_simulation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_simulation_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_get_simulation" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_get_simulation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetSimulationRequest.pb( + securitycenter_service.GetSimulationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = simulation.Simulation.to_json( + simulation.Simulation() + ) + + request = securitycenter_service.GetSimulationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = simulation.Simulation() + + client.get_simulation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_simulation_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.GetSimulationRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/simulations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_simulation(request) + + +def test_get_simulation_rest_flattened(): + client = SecurityCenterClient( + 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 = simulation.Simulation() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/simulations/sample2"} + + # 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 = simulation.Simulation.pb(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_simulation(**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/v2/{name=organizations/*/simulations/*}" % client.transport._host, + args[1], + ) + + +def test_get_simulation_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_simulation( + securitycenter_service.GetSimulationRequest(), + name="name_value", + ) + + +def test_get_simulation_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.GetValuedResourceRequest, + dict, + ], +) +def test_get_valued_resource_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource( + name="name_value", + resource="resource_value", + resource_type="resource_type_value", + display_name="display_name_value", + resource_value=valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW, + exposed_score=0.1395, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = valued_resource.ValuedResource.pb(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_valued_resource(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, valued_resource.ValuedResource) + assert response.name == "name_value" + assert response.resource == "resource_value" + assert response.resource_type == "resource_type_value" + assert response.display_name == "display_name_value" + assert ( + response.resource_value + == valued_resource.ValuedResource.ResourceValue.RESOURCE_VALUE_LOW + ) + assert math.isclose(response.exposed_score, 0.1395, rel_tol=1e-6) + + +def test_get_valued_resource_rest_required_fields( + request_type=securitycenter_service.GetValuedResourceRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_valued_resource._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_valued_resource._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = valued_resource.ValuedResource() + # 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 = valued_resource.ValuedResource.pb(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_valued_resource(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_valued_resource_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_valued_resource._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_valued_resource_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_get_valued_resource" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_get_valued_resource" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetValuedResourceRequest.pb( + securitycenter_service.GetValuedResourceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = valued_resource.ValuedResource.to_json( + valued_resource.ValuedResource() + ) + + request = securitycenter_service.GetValuedResourceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = valued_resource.ValuedResource() + + client.get_valued_resource( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_valued_resource_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.GetValuedResourceRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/simulations/sample2/valuedResources/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_valued_resource(request) + + +def test_get_valued_resource_rest_flattened(): + client = SecurityCenterClient( + 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 = valued_resource.ValuedResource() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/simulations/sample2/valuedResources/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 = valued_resource.ValuedResource.pb(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_valued_resource(**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/v2/{name=organizations/*/simulations/*/valuedResources/*}" + % client.transport._host, + args[1], + ) + + +def test_get_valued_resource_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_valued_resource( + securitycenter_service.GetValuedResourceRequest(), + name="name_value", + ) + + +def test_get_valued_resource_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + # 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 + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_rest_required_fields( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request + 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.get_iam_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("resource",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_get_iam_policy" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_get_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "organizations/sample1/sources/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = SecurityCenterClient( + 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 = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"resource": "organizations/sample1/sources/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + resource="resource_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.get_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{resource=organizations/*/sources/*}:getIamPolicy" + % client.transport._host, + args[1], + ) + + +def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource="resource_value", + ) + + +def test_get_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.GetMuteConfigRequest, + dict, + ], +) +def test_get_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/muteConfigs/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 = mute_config.MuteConfig( + name="name_value", + description="description_value", + filter="filter_value", + most_recent_editor="most_recent_editor_value", + type_=mute_config.MuteConfig.MuteConfigType.STATIC, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = mute_config.MuteConfig.pb(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_mute_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, mute_config.MuteConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == mute_config.MuteConfig.MuteConfigType.STATIC + + +def test_get_mute_config_rest_required_fields( + request_type=securitycenter_service.GetMuteConfigRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_mute_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_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = mute_config.MuteConfig() + # 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 = mute_config.MuteConfig.pb(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_mute_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_get_mute_config" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_get_mute_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetMuteConfigRequest.pb( + securitycenter_service.GetMuteConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = mute_config.MuteConfig.to_json( + mute_config.MuteConfig() + ) + + request = securitycenter_service.GetMuteConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = mute_config.MuteConfig() + + client.get_mute_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_mute_config_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.GetMuteConfigRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/muteConfigs/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_mute_config(request) + + +def test_get_mute_config_rest_flattened(): + client = SecurityCenterClient( + 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 = mute_config.MuteConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/muteConfigs/sample2"} + + # 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 = mute_config.MuteConfig.pb(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_mute_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/v2/{name=organizations/*/muteConfigs/*}" % client.transport._host, + args[1], + ) + + +def test_get_mute_config_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_mute_config( + securitycenter_service.GetMuteConfigRequest(), + name="name_value", + ) + + +def test_get_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.GetNotificationConfigRequest, + dict, + ], +) +def test_get_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/notificationConfigs/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 = notification_config.NotificationConfig( + name="name_value", + description="description_value", + pubsub_topic="pubsub_topic_value", + service_account="service_account_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 = notification_config.NotificationConfig.pb(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_notification_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.pubsub_topic == "pubsub_topic_value" + assert response.service_account == "service_account_value" + + +def test_get_notification_config_rest_required_fields( + request_type=securitycenter_service.GetNotificationConfigRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_notification_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = notification_config.NotificationConfig() + # 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 = notification_config.NotificationConfig.pb(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_notification_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_get_notification_config" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_get_notification_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetNotificationConfigRequest.pb( + securitycenter_service.GetNotificationConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = notification_config.NotificationConfig.to_json( + notification_config.NotificationConfig() + ) + + request = securitycenter_service.GetNotificationConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = notification_config.NotificationConfig() + + client.get_notification_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_notification_config_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.GetNotificationConfigRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "organizations/sample1/locations/sample2/notificationConfigs/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_notification_config(request) + + +def test_get_notification_config_rest_flattened(): + client = SecurityCenterClient( + 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 = notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/locations/sample2/notificationConfigs/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 = notification_config.NotificationConfig.pb(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_notification_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/v2/{name=organizations/*/locations/*/notificationConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_get_notification_config_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_notification_config( + securitycenter_service.GetNotificationConfigRequest(), + name="name_value", + ) + + +def test_get_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.GetResourceValueConfigRequest, + dict, + ], +) +def test_get_resource_value_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/resourceValueConfigs/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 = resource_value_config.ResourceValueConfig( + name="name_value", + resource_value=resource_value_config.ResourceValue.HIGH, + tag_values=["tag_values_value"], + resource_type="resource_type_value", + scope="scope_value", + description="description_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 = resource_value_config.ResourceValueConfig.pb(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_resource_value_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resource_value_config.ResourceValueConfig) + assert response.name == "name_value" + assert response.resource_value == resource_value_config.ResourceValue.HIGH + assert response.tag_values == ["tag_values_value"] + assert response.resource_type == "resource_type_value" + assert response.scope == "scope_value" + assert response.description == "description_value" + + +def test_get_resource_value_config_rest_required_fields( + request_type=securitycenter_service.GetResourceValueConfigRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_resource_value_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_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resource_value_config.ResourceValueConfig() + # 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 = resource_value_config.ResourceValueConfig.pb(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_resource_value_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_resource_value_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_resource_value_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_resource_value_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_get_resource_value_config" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_get_resource_value_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetResourceValueConfigRequest.pb( + securitycenter_service.GetResourceValueConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resource_value_config.ResourceValueConfig.to_json( + resource_value_config.ResourceValueConfig() + ) + + request = securitycenter_service.GetResourceValueConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resource_value_config.ResourceValueConfig() + + client.get_resource_value_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_resource_value_config_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.GetResourceValueConfigRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/resourceValueConfigs/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_resource_value_config(request) + + +def test_get_resource_value_config_rest_flattened(): + client = SecurityCenterClient( + 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 = resource_value_config.ResourceValueConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/resourceValueConfigs/sample2"} + + # 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 = resource_value_config.ResourceValueConfig.pb(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_resource_value_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/v2/{name=organizations/*/resourceValueConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_get_resource_value_config_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_resource_value_config( + securitycenter_service.GetResourceValueConfigRequest(), + name="name_value", + ) + + +def test_get_resource_value_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.GetSourceRequest, + dict, + ], +) +def test_get_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/sources/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 = source.Source( + name="name_value", + display_name="display_name_value", + description="description_value", + canonical_name="canonical_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 = source.Source.pb(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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" + + +def test_get_source_rest_required_fields( + request_type=securitycenter_service.GetSourceRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_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_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = source.Source() + # 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 = source.Source.pb(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_source(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_get_source" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_get_source" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GetSourceRequest.pb( + securitycenter_service.GetSourceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = source.Source.to_json(source.Source()) + + request = securitycenter_service.GetSourceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = source.Source() + + client.get_source( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_source_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.GetSourceRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/sources/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_source(request) + + +def test_get_source_rest_flattened(): + client = SecurityCenterClient( + 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 = source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/sources/sample2"} + + # 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 = source.Source.pb(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_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/v2/{name=organizations/*/sources/*}" % client.transport._host, args[1] + ) + + +def test_get_source_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_source( + securitycenter_service.GetSourceRequest(), + name="name_value", + ) + + +def test_get_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.GroupFindingsRequest, + dict, + ], +) +def test_group_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/sources/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 = securitycenter_service.GroupFindingsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.GroupFindingsResponse.pb(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.group_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +def test_group_findings_rest_required_fields( + request_type=securitycenter_service.GroupFindingsRequest, +): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["group_by"] = "" + 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() + ).group_findings._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" + jsonified_request["groupBy"] = "group_by_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).group_findings._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" + assert "groupBy" in jsonified_request + assert jsonified_request["groupBy"] == "group_by_value" + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.GroupFindingsResponse() + # 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 = securitycenter_service.GroupFindingsResponse.pb(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.group_findings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_group_findings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.group_findings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "groupBy", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_group_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_group_findings" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_group_findings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.GroupFindingsRequest.pb( + securitycenter_service.GroupFindingsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + securitycenter_service.GroupFindingsResponse.to_json( + securitycenter_service.GroupFindingsResponse() + ) + ) + + request = securitycenter_service.GroupFindingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.GroupFindingsResponse() + + client.group_findings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_group_findings_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.GroupFindingsRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/sources/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.group_findings(request) + + +def test_group_findings_rest_flattened(): + client = SecurityCenterClient( + 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 = securitycenter_service.GroupFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1/sources/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + group_by="group_by_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 = securitycenter_service.GroupFindingsResponse.pb(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.group_findings(**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/v2/{parent=organizations/*/sources/*}/findings:group" + % client.transport._host, + args[1], + ) + + +def test_group_findings_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent="parent_value", + group_by="group_by_value", + ) + + +def test_group_findings_rest_pager(transport: str = "rest"): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token="abc", + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token="def", + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token="ghi", + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + securitycenter_service.GroupFindingsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "organizations/sample1/sources/sample2"} + + pager = client.group_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) for i in results) + + pages = list(client.group_findings(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.ListAttackPathsRequest, + dict, + ], +) +def test_list_attack_paths_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse( + next_page_token="next_page_token_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 = securitycenter_service.ListAttackPathsResponse.pb(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_attack_paths(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttackPathsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_attack_paths_rest_required_fields( + request_type=securitycenter_service.ListAttackPathsRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_attack_paths._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_attack_paths._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListAttackPathsResponse() + # 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 = securitycenter_service.ListAttackPathsResponse.pb( + 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_attack_paths(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_attack_paths_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_attack_paths._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_attack_paths_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_list_attack_paths" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_list_attack_paths" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListAttackPathsRequest.pb( + securitycenter_service.ListAttackPathsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + securitycenter_service.ListAttackPathsResponse.to_json( + securitycenter_service.ListAttackPathsResponse() + ) + ) + + request = securitycenter_service.ListAttackPathsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListAttackPathsResponse() + + client.list_attack_paths( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_attack_paths_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.ListAttackPathsRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/simulations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_attack_paths(request) + + +def test_list_attack_paths_rest_flattened(): + client = SecurityCenterClient( + 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 = securitycenter_service.ListAttackPathsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1/simulations/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 = securitycenter_service.ListAttackPathsResponse.pb(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_attack_paths(**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/v2/{parent=organizations/*/simulations/*}/attackPaths" + % client.transport._host, + args[1], + ) + + +def test_list_attack_paths_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_attack_paths( + securitycenter_service.ListAttackPathsRequest(), + parent="parent_value", + ) + + +def test_list_attack_paths_rest_pager(transport: str = "rest"): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + next_page_token="abc", + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[], + next_page_token="def", + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListAttackPathsResponse( + attack_paths=[ + attack_path.AttackPath(), + attack_path.AttackPath(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + securitycenter_service.ListAttackPathsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "organizations/sample1/simulations/sample2"} + + pager = client.list_attack_paths(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, attack_path.AttackPath) for i in results) + + pages = list(client.list_attack_paths(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.ListBigQueryExportsRequest, + dict, + ], +) +def test_list_big_query_exports_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = securitycenter_service.ListBigQueryExportsResponse( + next_page_token="next_page_token_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 = securitycenter_service.ListBigQueryExportsResponse.pb( + 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_big_query_exports(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryExportsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_big_query_exports_rest_required_fields( + request_type=securitycenter_service.ListBigQueryExportsRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_big_query_exports._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_big_query_exports._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListBigQueryExportsResponse() + # 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 = securitycenter_service.ListBigQueryExportsResponse.pb( + 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_big_query_exports(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_big_query_exports_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_big_query_exports._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_big_query_exports_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_list_big_query_exports" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_list_big_query_exports" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListBigQueryExportsRequest.pb( + securitycenter_service.ListBigQueryExportsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + securitycenter_service.ListBigQueryExportsResponse.to_json( + securitycenter_service.ListBigQueryExportsResponse() + ) + ) + + request = securitycenter_service.ListBigQueryExportsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListBigQueryExportsResponse() + + client.list_big_query_exports( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_big_query_exports_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.ListBigQueryExportsRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_big_query_exports(request) + + +def test_list_big_query_exports_rest_flattened(): + client = SecurityCenterClient( + 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 = securitycenter_service.ListBigQueryExportsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/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 = securitycenter_service.ListBigQueryExportsResponse.pb( + 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_big_query_exports(**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/v2/{parent=organizations/*/locations/*}/bigQueryExports" + % client.transport._host, + args[1], + ) + + +def test_list_big_query_exports_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_big_query_exports( + securitycenter_service.ListBigQueryExportsRequest(), + parent="parent_value", + ) + + +def test_list_big_query_exports_rest_pager(transport: str = "rest"): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + next_page_token="abc", + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[], + next_page_token="def", + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListBigQueryExportsResponse( + big_query_exports=[ + bigquery_export.BigQueryExport(), + bigquery_export.BigQueryExport(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + securitycenter_service.ListBigQueryExportsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "organizations/sample1/locations/sample2"} + + pager = client.list_big_query_exports(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, bigquery_export.BigQueryExport) for i in results) + + pages = list(client.list_big_query_exports(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.ListFindingsRequest, + dict, + ], +) +def test_list_findings_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListFindingsResponse.pb(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_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +def test_list_findings_rest_required_fields( + request_type=securitycenter_service.ListFindingsRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_findings._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_findings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "field_mask", + "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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListFindingsResponse() + # 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 = securitycenter_service.ListFindingsResponse.pb(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_findings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_findings_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_findings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "fieldMask", + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_findings_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_list_findings" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_list_findings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListFindingsRequest.pb( + securitycenter_service.ListFindingsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListFindingsResponse.to_json( + securitycenter_service.ListFindingsResponse() + ) + + request = securitycenter_service.ListFindingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListFindingsResponse() + + client.list_findings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_findings_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.ListFindingsRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/sources/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_findings(request) + + +def test_list_findings_rest_flattened(): + client = SecurityCenterClient( + 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 = securitycenter_service.ListFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1/sources/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 = securitycenter_service.ListFindingsResponse.pb(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_findings(**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/v2/{parent=organizations/*/sources/*}/findings" + % client.transport._host, + args[1], + ) + + +def test_list_findings_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_findings( + securitycenter_service.ListFindingsRequest(), + parent="parent_value", + ) + + +def test_list_findings_rest_pager(transport: str = "rest"): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token="abc", + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token="def", + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + securitycenter_service.ListFindingsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "organizations/sample1/sources/sample2"} + + pager = client.list_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance( + i, securitycenter_service.ListFindingsResponse.ListFindingsResult + ) + for i in results + ) + + pages = list(client.list_findings(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.ListMuteConfigsRequest, + dict, + ], +) +def test_list_mute_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListMuteConfigsResponse( + next_page_token="next_page_token_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 = securitycenter_service.ListMuteConfigsResponse.pb(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_mute_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMuteConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_mute_configs_rest_required_fields( + request_type=securitycenter_service.ListMuteConfigsRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_mute_configs._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_mute_configs._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListMuteConfigsResponse() + # 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 = securitycenter_service.ListMuteConfigsResponse.pb( + 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_mute_configs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_mute_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_mute_configs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_mute_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_list_mute_configs" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_list_mute_configs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListMuteConfigsRequest.pb( + securitycenter_service.ListMuteConfigsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + securitycenter_service.ListMuteConfigsResponse.to_json( + securitycenter_service.ListMuteConfigsResponse() + ) + ) + + request = securitycenter_service.ListMuteConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListMuteConfigsResponse() + + client.list_mute_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_mute_configs_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.ListMuteConfigsRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_mute_configs(request) + + +def test_list_mute_configs_rest_flattened(): + client = SecurityCenterClient( + 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 = securitycenter_service.ListMuteConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # 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 = securitycenter_service.ListMuteConfigsResponse.pb(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_mute_configs(**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/v2/{parent=organizations/*}/muteConfigs" % client.transport._host, + args[1], + ) + + +def test_list_mute_configs_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_mute_configs( + securitycenter_service.ListMuteConfigsRequest(), + parent="parent_value", + ) + + +def test_list_mute_configs_rest_pager(transport: str = "rest"): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + next_page_token="abc", + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[], + next_page_token="def", + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListMuteConfigsResponse( + mute_configs=[ + mute_config.MuteConfig(), + mute_config.MuteConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + securitycenter_service.ListMuteConfigsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "organizations/sample1"} + + pager = client.list_mute_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, mute_config.MuteConfig) for i in results) + + pages = list(client.list_mute_configs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.ListNotificationConfigsRequest, + dict, + ], +) +def test_list_notification_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = securitycenter_service.ListNotificationConfigsResponse( + next_page_token="next_page_token_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 = securitycenter_service.ListNotificationConfigsResponse.pb( + 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_notification_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_notification_configs_rest_required_fields( + request_type=securitycenter_service.ListNotificationConfigsRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_notification_configs._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_notification_configs._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListNotificationConfigsResponse() + # 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 = securitycenter_service.ListNotificationConfigsResponse.pb( + 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_notification_configs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_notification_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_notification_configs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_notification_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_list_notification_configs" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_list_notification_configs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListNotificationConfigsRequest.pb( + securitycenter_service.ListNotificationConfigsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + securitycenter_service.ListNotificationConfigsResponse.to_json( + securitycenter_service.ListNotificationConfigsResponse() + ) + ) + + request = securitycenter_service.ListNotificationConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListNotificationConfigsResponse() + + client.list_notification_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_notification_configs_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.ListNotificationConfigsRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_notification_configs(request) + + +def test_list_notification_configs_rest_flattened(): + client = SecurityCenterClient( + 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 = securitycenter_service.ListNotificationConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/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 = securitycenter_service.ListNotificationConfigsResponse.pb( + 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_notification_configs(**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/v2/{parent=organizations/*/locations/*}/notificationConfigs" + % client.transport._host, + args[1], + ) + + +def test_list_notification_configs_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_notification_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent="parent_value", + ) + + +def test_list_notification_configs_rest_pager(transport: str = "rest"): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token="abc", + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token="def", + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + securitycenter_service.ListNotificationConfigsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "organizations/sample1/locations/sample2"} + + pager = client.list_notification_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, notification_config.NotificationConfig) for i in results + ) + + pages = list(client.list_notification_configs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.ListResourceValueConfigsRequest, + dict, + ], +) +def test_list_resource_value_configs_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListResourceValueConfigsResponse( + next_page_token="next_page_token_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 = securitycenter_service.ListResourceValueConfigsResponse.pb( + 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_resource_value_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceValueConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_resource_value_configs_rest_required_fields( + request_type=securitycenter_service.ListResourceValueConfigsRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_resource_value_configs._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_resource_value_configs._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListResourceValueConfigsResponse() + # 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 = securitycenter_service.ListResourceValueConfigsResponse.pb( + 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_resource_value_configs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_resource_value_configs_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_resource_value_configs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_resource_value_configs_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_list_resource_value_configs" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_list_resource_value_configs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListResourceValueConfigsRequest.pb( + securitycenter_service.ListResourceValueConfigsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + securitycenter_service.ListResourceValueConfigsResponse.to_json( + securitycenter_service.ListResourceValueConfigsResponse() + ) + ) + + request = securitycenter_service.ListResourceValueConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListResourceValueConfigsResponse() + + client.list_resource_value_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_resource_value_configs_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.ListResourceValueConfigsRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_resource_value_configs(request) + + +def test_list_resource_value_configs_rest_flattened(): + client = SecurityCenterClient( + 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 = securitycenter_service.ListResourceValueConfigsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # 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 = securitycenter_service.ListResourceValueConfigsResponse.pb( + 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_resource_value_configs(**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/v2/{parent=organizations/*}/resourceValueConfigs" + % client.transport._host, + args[1], + ) + + +def test_list_resource_value_configs_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_resource_value_configs( + securitycenter_service.ListResourceValueConfigsRequest(), + parent="parent_value", + ) + + +def test_list_resource_value_configs_rest_pager(transport: str = "rest"): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + next_page_token="abc", + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[], + next_page_token="def", + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListResourceValueConfigsResponse( + resource_value_configs=[ + resource_value_config.ResourceValueConfig(), + resource_value_config.ResourceValueConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + securitycenter_service.ListResourceValueConfigsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "organizations/sample1"} + + pager = client.list_resource_value_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, resource_value_config.ResourceValueConfig) for i in results + ) + + pages = list(client.list_resource_value_configs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.ListSourcesRequest, + dict, + ], +) +def test_list_sources_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse( + next_page_token="next_page_token_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 = securitycenter_service.ListSourcesResponse.pb(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_sources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_sources_rest_required_fields( + request_type=securitycenter_service.ListSourcesRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_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_sources._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListSourcesResponse() + # 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 = securitycenter_service.ListSourcesResponse.pb(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_sources(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_sources_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_sources._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sources_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_list_sources" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_list_sources" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListSourcesRequest.pb( + securitycenter_service.ListSourcesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = securitycenter_service.ListSourcesResponse.to_json( + securitycenter_service.ListSourcesResponse() + ) + + request = securitycenter_service.ListSourcesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListSourcesResponse() + + client.list_sources( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_sources_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.ListSourcesRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_sources(request) + + +def test_list_sources_rest_flattened(): + client = SecurityCenterClient( + 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 = securitycenter_service.ListSourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # 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 = securitycenter_service.ListSourcesResponse.pb(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_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/v2/{parent=organizations/*}/sources" % client.transport._host, args[1] + ) + + +def test_list_sources_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_sources( + securitycenter_service.ListSourcesRequest(), + parent="parent_value", + ) + + +def test_list_sources_rest_pager(transport: str = "rest"): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token="abc", + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token="def", + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + securitycenter_service.ListSourcesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "organizations/sample1"} + + pager = client.list_sources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, source.Source) for i in results) + + pages = list(client.list_sources(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.ListValuedResourcesRequest, + dict, + ], +) +def test_list_valued_resources_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = securitycenter_service.ListValuedResourcesResponse.pb( + 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_valued_resources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListValuedResourcesPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +def test_list_valued_resources_rest_required_fields( + request_type=securitycenter_service.ListValuedResourcesRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_valued_resources._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_valued_resources._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = securitycenter_service.ListValuedResourcesResponse() + # 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 = securitycenter_service.ListValuedResourcesResponse.pb( + 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_valued_resources(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_valued_resources_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_valued_resources._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_valued_resources_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_list_valued_resources" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_list_valued_resources" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.ListValuedResourcesRequest.pb( + securitycenter_service.ListValuedResourcesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + securitycenter_service.ListValuedResourcesResponse.to_json( + securitycenter_service.ListValuedResourcesResponse() + ) + ) + + request = securitycenter_service.ListValuedResourcesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = securitycenter_service.ListValuedResourcesResponse() + + client.list_valued_resources( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_valued_resources_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.ListValuedResourcesRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1/simulations/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_valued_resources(request) + + +def test_list_valued_resources_rest_flattened(): + client = SecurityCenterClient( + 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 = securitycenter_service.ListValuedResourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1/simulations/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 = securitycenter_service.ListValuedResourcesResponse.pb( + 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_valued_resources(**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/v2/{parent=organizations/*/simulations/*}/valuedResources" + % client.transport._host, + args[1], + ) + + +def test_list_valued_resources_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_valued_resources( + securitycenter_service.ListValuedResourcesRequest(), + parent="parent_value", + ) + + +def test_list_valued_resources_rest_pager(transport: str = "rest"): + client = SecurityCenterClient( + 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 = ( + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + next_page_token="abc", + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[], + next_page_token="def", + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + ], + next_page_token="ghi", + ), + securitycenter_service.ListValuedResourcesResponse( + valued_resources=[ + valued_resource.ValuedResource(), + valued_resource.ValuedResource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + securitycenter_service.ListValuedResourcesResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "organizations/sample1/simulations/sample2"} + + pager = client.list_valued_resources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, valued_resource.ValuedResource) for i in results) + + pages = list(client.list_valued_resources(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.SetFindingStateRequest, + dict, + ], +) +def test_set_finding_state_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/sources/sample2/findings/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 = finding.Finding( + name="name_value", + canonical_name="canonical_name_value", + parent="parent_value", + resource_name="resource_name_value", + state=finding.Finding.State.ACTIVE, + category="category_value", + external_uri="external_uri_value", + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator="mute_initiator_value", + parent_display_name="parent_display_name_value", + description="description_value", + next_steps="next_steps_value", + module_name="module_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 = finding.Finding.pb(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.set_finding_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" + assert response.parent == "parent_value" + assert response.resource_name == "resource_name_value" + assert response.state == finding.Finding.State.ACTIVE + assert response.category == "category_value" + assert response.external_uri == "external_uri_value" + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == "mute_initiator_value" + assert response.parent_display_name == "parent_display_name_value" + assert response.description == "description_value" + assert response.next_steps == "next_steps_value" + assert response.module_name == "module_name_value" + + +def test_set_finding_state_rest_required_fields( + request_type=securitycenter_service.SetFindingStateRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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() + ).set_finding_state._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() + ).set_finding_state._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = finding.Finding() + # 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 = finding.Finding.pb(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.set_finding_state(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_finding_state_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_finding_state._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "state", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_finding_state_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_set_finding_state" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_set_finding_state" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.SetFindingStateRequest.pb( + securitycenter_service.SetFindingStateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = finding.Finding.to_json(finding.Finding()) + + request = securitycenter_service.SetFindingStateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.set_finding_state( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_finding_state_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.SetFindingStateRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_finding_state(request) + + +def test_set_finding_state_rest_flattened(): + client = SecurityCenterClient( + 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 = finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/sources/sample2/findings/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + state=finding.Finding.State.ACTIVE, + ) + 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 = finding.Finding.pb(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.set_finding_state(**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/v2/{name=organizations/*/sources/*/findings/*}:setState" + % client.transport._host, + args[1], + ) + + +def test_set_finding_state_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name="name_value", + state=finding.Finding.State.ACTIVE, + ) + + +def test_set_finding_state_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "organizations/sample1/sources/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 = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + # 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 + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_rest_required_fields( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request + 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.set_iam_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "resource", + "policy", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_set_iam_policy" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_set_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "organizations/sample1/sources/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = SecurityCenterClient( + 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 = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"resource": "organizations/sample1/sources/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + resource="resource_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.set_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{resource=organizations/*/sources/*}:setIamPolicy" + % client.transport._host, + args[1], + ) + + +def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource="resource_value", + ) + + +def test_set_iam_policy_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.SetMuteRequest, + dict, + ], +) +def test_set_mute_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/sources/sample2/findings/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 = finding.Finding( + name="name_value", + canonical_name="canonical_name_value", + parent="parent_value", + resource_name="resource_name_value", + state=finding.Finding.State.ACTIVE, + category="category_value", + external_uri="external_uri_value", + severity=finding.Finding.Severity.CRITICAL, + mute=finding.Finding.Mute.MUTED, + finding_class=finding.Finding.FindingClass.THREAT, + mute_initiator="mute_initiator_value", + parent_display_name="parent_display_name_value", + description="description_value", + next_steps="next_steps_value", + module_name="module_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 = finding.Finding.pb(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.set_mute(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" + assert response.parent == "parent_value" + assert response.resource_name == "resource_name_value" + assert response.state == finding.Finding.State.ACTIVE + assert response.category == "category_value" + assert response.external_uri == "external_uri_value" + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.mute == finding.Finding.Mute.MUTED + assert response.finding_class == finding.Finding.FindingClass.THREAT + assert response.mute_initiator == "mute_initiator_value" + assert response.parent_display_name == "parent_display_name_value" + assert response.description == "description_value" + assert response.next_steps == "next_steps_value" + assert response.module_name == "module_name_value" + + +def test_set_mute_rest_required_fields( + request_type=securitycenter_service.SetMuteRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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() + ).set_mute._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() + ).set_mute._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = finding.Finding() + # 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 = finding.Finding.pb(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.set_mute(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_mute_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_mute._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "mute", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_mute_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_set_mute" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_set_mute" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.SetMuteRequest.pb( + securitycenter_service.SetMuteRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = finding.Finding.to_json(finding.Finding()) + + request = securitycenter_service.SetMuteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.set_mute( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_mute_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.SetMuteRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_mute(request) + + +def test_set_mute_rest_flattened(): + client = SecurityCenterClient( + 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 = finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "organizations/sample1/sources/sample2/findings/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + mute=finding.Finding.Mute.MUTED, + ) + 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 = finding.Finding.pb(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.set_mute(**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/v2/{name=organizations/*/sources/*/findings/*}:setMute" + % client.transport._host, + args[1], + ) + + +def test_set_mute_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_mute( + securitycenter_service.SetMuteRequest(), + name="name_value", + mute=finding.Finding.Mute.MUTED, + ) + + +def test_set_mute_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "organizations/sample1/sources/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 = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_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 + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_rest_required_fields( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + transport_class = transports.SecurityCenterRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = "resource_value" + jsonified_request["permissions"] = "permissions_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == "permissions_value" + + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # 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 + 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.test_iam_permissions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "resource", + "permissions", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_test_iam_permissions" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_test_iam_permissions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "organizations/sample1/sources/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = SecurityCenterClient( + 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 = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"resource": "organizations/sample1/sources/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + resource="resource_value", + permissions=["permissions_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.test_iam_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{resource=organizations/*/sources/*}:testIamPermissions" + % client.transport._host, + args[1], + ) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +def test_test_iam_permissions_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.UpdateBigQueryExportRequest, + dict, + ], +) +def test_update_big_query_export_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "big_query_export": { + "name": "organizations/sample1/locations/sample2/bigQueryExports/sample3" + } + } + request_init["big_query_export"] = { + "name": "organizations/sample1/locations/sample2/bigQueryExports/sample3", + "description": "description_value", + "filter": "filter_value", + "dataset": "dataset_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "most_recent_editor": "most_recent_editor_value", + "principal": "principal_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 = securitycenter_service.UpdateBigQueryExportRequest.meta.fields[ + "big_query_export" + ] + + 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["big_query_export"].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["big_query_export"][field])): + del request_init["big_query_export"][field][i][subfield] + else: + del request_init["big_query_export"][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 = bigquery_export.BigQueryExport( + name="name_value", + description="description_value", + filter="filter_value", + dataset="dataset_value", + most_recent_editor="most_recent_editor_value", + principal="principal_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 = bigquery_export.BigQueryExport.pb(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_big_query_export(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, bigquery_export.BigQueryExport) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.dataset == "dataset_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.principal == "principal_value" + + +def test_update_big_query_export_rest_required_fields( + request_type=securitycenter_service.UpdateBigQueryExportRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_big_query_export._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_big_query_export._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bigquery_export.BigQueryExport() + # 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 = bigquery_export.BigQueryExport.pb(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_big_query_export(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_big_query_export_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_big_query_export._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("bigQueryExport",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_big_query_export_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_update_big_query_export" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_update_big_query_export" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateBigQueryExportRequest.pb( + securitycenter_service.UpdateBigQueryExportRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = bigquery_export.BigQueryExport.to_json( + bigquery_export.BigQueryExport() + ) + + request = securitycenter_service.UpdateBigQueryExportRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = bigquery_export.BigQueryExport() + + client.update_big_query_export( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_big_query_export_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.UpdateBigQueryExportRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "big_query_export": { + "name": "organizations/sample1/locations/sample2/bigQueryExports/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_big_query_export(request) + + +def test_update_big_query_export_rest_flattened(): + client = SecurityCenterClient( + 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 = bigquery_export.BigQueryExport() + + # get arguments that satisfy an http rule for this method + sample_request = { + "big_query_export": { + "name": "organizations/sample1/locations/sample2/bigQueryExports/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + big_query_export=bigquery_export.BigQueryExport(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 = bigquery_export.BigQueryExport.pb(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_big_query_export(**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/v2/{big_query_export.name=organizations/*/locations/*/bigQueryExports/*}" + % client.transport._host, + args[1], + ) + + +def test_update_big_query_export_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_big_query_export( + securitycenter_service.UpdateBigQueryExportRequest(), + big_query_export=bigquery_export.BigQueryExport(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_big_query_export_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.UpdateExternalSystemRequest, + dict, + ], +) +def test_update_external_system_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "external_system": { + "name": "organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4" + } + } + request_init["external_system"] = { + "name": "organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4", + "assignees": ["assignees_value1", "assignees_value2"], + "external_uid": "external_uid_value", + "status": "status_value", + "external_system_update_time": {"seconds": 751, "nanos": 543}, + "case_uri": "case_uri_value", + "case_priority": "case_priority_value", + "case_sla": {}, + "case_create_time": {}, + "case_close_time": {}, + "ticket_info": { + "id": "id_value", + "assignee": "assignee_value", + "description": "description_value", + "uri": "uri_value", + "status": "status_value", + "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 + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = securitycenter_service.UpdateExternalSystemRequest.meta.fields[ + "external_system" + ] + + 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["external_system"].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["external_system"][field])): + del request_init["external_system"][field][i][subfield] + else: + del request_init["external_system"][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 = gcs_external_system.ExternalSystem( + name="name_value", + assignees=["assignees_value"], + external_uid="external_uid_value", + status="status_value", + case_uri="case_uri_value", + case_priority="case_priority_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 = gcs_external_system.ExternalSystem.pb(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_external_system(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_external_system.ExternalSystem) + assert response.name == "name_value" + assert response.assignees == ["assignees_value"] + assert response.external_uid == "external_uid_value" + assert response.status == "status_value" + assert response.case_uri == "case_uri_value" + assert response.case_priority == "case_priority_value" + + +def test_update_external_system_rest_required_fields( + request_type=securitycenter_service.UpdateExternalSystemRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_external_system._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_external_system._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_external_system.ExternalSystem() + # 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 = gcs_external_system.ExternalSystem.pb(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_external_system(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_external_system_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_external_system._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("externalSystem",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_external_system_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_update_external_system" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_update_external_system" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateExternalSystemRequest.pb( + securitycenter_service.UpdateExternalSystemRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_external_system.ExternalSystem.to_json( + gcs_external_system.ExternalSystem() + ) + + request = securitycenter_service.UpdateExternalSystemRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_external_system.ExternalSystem() + + client.update_external_system( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_external_system_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.UpdateExternalSystemRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "external_system": { + "name": "organizations/sample1/sources/sample2/findings/sample3/externalSystems/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_external_system(request) + + +def test_update_external_system_rest_flattened(): + client = SecurityCenterClient( + 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 = gcs_external_system.ExternalSystem() + + # get arguments that satisfy an http rule for this method + sample_request = { + "external_system": { + "name": "organizations/sample1/sources/sample2/findings/sample3/externalSystems/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + external_system=gcs_external_system.ExternalSystem(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 = gcs_external_system.ExternalSystem.pb(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_external_system(**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/v2/{external_system.name=organizations/*/sources/*/findings/*/externalSystems/*}" + % client.transport._host, + args[1], + ) + + +def test_update_external_system_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_external_system( + securitycenter_service.UpdateExternalSystemRequest(), + external_system=gcs_external_system.ExternalSystem(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_external_system_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.UpdateFindingRequest, + dict, + ], +) +def test_update_finding_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "finding": {"name": "organizations/sample1/sources/sample2/findings/sample3"} + } + request_init["finding"] = { + "name": "organizations/sample1/sources/sample2/findings/sample3", + "canonical_name": "canonical_name_value", + "parent": "parent_value", + "resource_name": "resource_name_value", + "state": 1, + "category": "category_value", + "external_uri": "external_uri_value", + "source_properties": {}, + "security_marks": { + "name": "name_value", + "marks": {}, + "canonical_name": "canonical_name_value", + }, + "event_time": {"seconds": 751, "nanos": 543}, + "create_time": {}, + "severity": 1, + "mute": 1, + "finding_class": 1, + "indicator": { + "ip_addresses": ["ip_addresses_value1", "ip_addresses_value2"], + "domains": ["domains_value1", "domains_value2"], + "signatures": [ + { + "memory_hash_signature": { + "binary_family": "binary_family_value", + "detections": [ + {"binary": "binary_value", "percent_pages_matched": 0.2197} + ], + }, + "yara_rule_signature": {"yara_rule": "yara_rule_value"}, + "signature_type": 1, + } + ], + "uris": ["uris_value1", "uris_value2"], + }, + "vulnerability": { + "cve": { + "id": "id_value", + "references": [{"source": "source_value", "uri": "uri_value"}], + "cvssv3": { + "base_score": 0.1046, + "attack_vector": 1, + "attack_complexity": 1, + "privileges_required": 1, + "user_interaction": 1, + "scope": 1, + "confidentiality_impact": 1, + "integrity_impact": 1, + "availability_impact": 1, + }, + "upstream_fix_available": True, + "impact": 1, + "exploitation_activity": 1, + "observed_in_the_wild": True, + "zero_day": True, + }, + "offending_package": { + "package_name": "package_name_value", + "cpe_uri": "cpe_uri_value", + "package_type": "package_type_value", + "package_version": "package_version_value", + }, + "fixed_package": {}, + "security_bulletin": { + "bulletin_id": "bulletin_id_value", + "submission_time": {}, + "suggested_upgrade_version": "suggested_upgrade_version_value", + }, + }, + "mute_update_time": {}, + "external_systems": {}, + "mitre_attack": { + "primary_tactic": 1, + "primary_techniques": [49], + "additional_tactics": [1], + "additional_techniques": [49], + "version": "version_value", + }, + "access": { + "principal_email": "principal_email_value", + "caller_ip": "caller_ip_value", + "caller_ip_geo": {"region_code": "region_code_value"}, + "user_agent_family": "user_agent_family_value", + "user_agent": "user_agent_value", + "service_name": "service_name_value", + "method_name": "method_name_value", + "principal_subject": "principal_subject_value", + "service_account_key_name": "service_account_key_name_value", + "service_account_delegation_info": [ + { + "principal_email": "principal_email_value", + "principal_subject": "principal_subject_value", + } + ], + "user_name": "user_name_value", + }, + "connections": [ + { + "destination_ip": "destination_ip_value", + "destination_port": 1734, + "source_ip": "source_ip_value", + "source_port": 1205, + "protocol": 1, + } + ], + "mute_initiator": "mute_initiator_value", + "processes": [ + { + "name": "name_value", + "binary": { + "path": "path_value", + "size": 443, + "sha256": "sha256_value", + "hashed_size": 1159, + "partially_hashed": True, + "contents": "contents_value", + "disk_path": { + "partition_uuid": "partition_uuid_value", + "relative_path": "relative_path_value", + }, + }, + "libraries": {}, + "script": {}, + "args": ["args_value1", "args_value2"], + "arguments_truncated": True, + "env_variables": [{"name": "name_value", "val": "val_value"}], + "env_variables_truncated": True, + "pid": 317, + "parent_pid": 1062, + } + ], + "contacts": {}, + "compliances": [ + { + "standard": "standard_value", + "version": "version_value", + "ids": ["ids_value1", "ids_value2"], + } + ], + "parent_display_name": "parent_display_name_value", + "description": "description_value", + "exfiltration": { + "sources": [ + { + "name": "name_value", + "components": ["components_value1", "components_value2"], + } + ], + "targets": {}, + "total_exfiltrated_bytes": 2469, + }, + "iam_bindings": [{"action": 1, "role": "role_value", "member": "member_value"}], + "next_steps": "next_steps_value", + "module_name": "module_name_value", + "containers": [ + { + "name": "name_value", + "uri": "uri_value", + "image_id": "image_id_value", + "labels": [{"name": "name_value", "value": "value_value"}], + "create_time": {}, + } + ], + "kubernetes": { + "pods": [ + {"ns": "ns_value", "name": "name_value", "labels": {}, "containers": {}} + ], + "nodes": [{"name": "name_value"}], + "node_pools": [{"name": "name_value", "nodes": {}}], + "roles": [{"kind": 1, "ns": "ns_value", "name": "name_value"}], + "bindings": [ + { + "ns": "ns_value", + "name": "name_value", + "role": {}, + "subjects": [{"kind": 1, "ns": "ns_value", "name": "name_value"}], + } + ], + "access_reviews": [ + { + "group": "group_value", + "ns": "ns_value", + "name": "name_value", + "resource": "resource_value", + "subresource": "subresource_value", + "verb": "verb_value", + "version": "version_value", + } + ], + "objects": [ + { + "group": "group_value", + "kind": "kind_value", + "ns": "ns_value", + "name": "name_value", + "containers": {}, + } + ], + }, + "database": { + "name": "name_value", + "display_name": "display_name_value", + "user_name": "user_name_value", + "query": "query_value", + "grantees": ["grantees_value1", "grantees_value2"], + "version": "version_value", + }, + "attack_exposure": { + "score": 0.54, + "latest_calculation_time": {}, + "attack_exposure_result": "attack_exposure_result_value", + "state": 1, + "exposed_high_value_resources_count": 3637, + "exposed_medium_value_resources_count": 3862, + "exposed_low_value_resources_count": 3559, + }, + "files": {}, + "cloud_dlp_inspection": { + "inspect_job": "inspect_job_value", + "info_type": "info_type_value", + "info_type_count": 1621, + "full_scan": True, + }, + "cloud_dlp_data_profile": { + "data_profile": "data_profile_value", + "parent_type": 1, + }, + "kernel_rootkit": { + "name": "name_value", + "unexpected_code_modification": True, + "unexpected_read_only_data_modification": True, + "unexpected_ftrace_handler": True, + "unexpected_kprobe_handler": True, + "unexpected_kernel_code_pages": True, + "unexpected_system_call_handler": True, + "unexpected_interrupt_handler": True, + "unexpected_processes_in_runqueue": True, + }, + "org_policies": [{"name": "name_value"}], + "application": {"base_uri": "base_uri_value", "full_uri": "full_uri_value"}, + "backup_disaster_recovery": { + "backup_template": "backup_template_value", + "policies": ["policies_value1", "policies_value2"], + "host": "host_value", + "applications": ["applications_value1", "applications_value2"], + "storage_pool": "storage_pool_value", + "policy_options": ["policy_options_value1", "policy_options_value2"], + "profile": "profile_value", + "appliance": "appliance_value", + "backup_type": "backup_type_value", + "backup_create_time": {}, + }, + "security_posture": { + "name": "name_value", + "revision_id": "revision_id_value", + "posture_deployment_resource": "posture_deployment_resource_value", + "posture_deployment": "posture_deployment_value", + "changed_policy": "changed_policy_value", + "policy_set": "policy_set_value", + "policy": "policy_value", + "policy_drift_details": [ + { + "field": "field_value", + "expected_value": "expected_value_value", + "detected_value": "detected_value_value", + } + ], + }, + "log_entries": [ + { + "cloud_logging_entry": { + "insert_id": "insert_id_value", + "log_id": "log_id_value", + "resource_container": "resource_container_value", + "timestamp": {}, + } + } + ], + "load_balancers": [{"name": "name_value"}], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = securitycenter_service.UpdateFindingRequest.meta.fields["finding"] + + 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["finding"].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["finding"][field])): + del request_init["finding"][field][i][subfield] + else: + del request_init["finding"][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 = gcs_finding.Finding( + name="name_value", + canonical_name="canonical_name_value", + parent="parent_value", + resource_name="resource_name_value", + state=gcs_finding.Finding.State.ACTIVE, + category="category_value", + external_uri="external_uri_value", + severity=gcs_finding.Finding.Severity.CRITICAL, + mute=gcs_finding.Finding.Mute.MUTED, + finding_class=gcs_finding.Finding.FindingClass.THREAT, + mute_initiator="mute_initiator_value", + parent_display_name="parent_display_name_value", + description="description_value", + next_steps="next_steps_value", + module_name="module_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 = gcs_finding.Finding.pb(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_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" + assert response.parent == "parent_value" + assert response.resource_name == "resource_name_value" + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == "category_value" + assert response.external_uri == "external_uri_value" + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.mute == gcs_finding.Finding.Mute.MUTED + assert response.finding_class == gcs_finding.Finding.FindingClass.THREAT + assert response.mute_initiator == "mute_initiator_value" + assert response.parent_display_name == "parent_display_name_value" + assert response.description == "description_value" + assert response.next_steps == "next_steps_value" + assert response.module_name == "module_name_value" + + +def test_update_finding_rest_required_fields( + request_type=securitycenter_service.UpdateFindingRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_finding._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_finding._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_finding.Finding() + # 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 = gcs_finding.Finding.pb(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_finding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_finding_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("finding",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_finding_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_update_finding" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_update_finding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateFindingRequest.pb( + securitycenter_service.UpdateFindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_finding.Finding.to_json(gcs_finding.Finding()) + + request = securitycenter_service.UpdateFindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_finding.Finding() + + client.update_finding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_finding_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.UpdateFindingRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "finding": {"name": "organizations/sample1/sources/sample2/findings/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_finding(request) + + +def test_update_finding_rest_flattened(): + client = SecurityCenterClient( + 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 = gcs_finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = { + "finding": { + "name": "organizations/sample1/sources/sample2/findings/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + finding=gcs_finding.Finding(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 = gcs_finding.Finding.pb(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_finding(**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/v2/{finding.name=organizations/*/sources/*/findings/*}" + % client.transport._host, + args[1], + ) + + +def test_update_finding_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_finding_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.UpdateMuteConfigRequest, + dict, + ], +) +def test_update_mute_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "mute_config": {"name": "organizations/sample1/muteConfigs/sample2"} + } + request_init["mute_config"] = { + "name": "organizations/sample1/muteConfigs/sample2", + "description": "description_value", + "filter": "filter_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "most_recent_editor": "most_recent_editor_value", + "type_": 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 = securitycenter_service.UpdateMuteConfigRequest.meta.fields[ + "mute_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["mute_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["mute_config"][field])): + del request_init["mute_config"][field][i][subfield] + else: + del request_init["mute_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 = gcs_mute_config.MuteConfig( + name="name_value", + description="description_value", + filter="filter_value", + most_recent_editor="most_recent_editor_value", + type_=gcs_mute_config.MuteConfig.MuteConfigType.STATIC, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_mute_config.MuteConfig.pb(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_mute_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_mute_config.MuteConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.filter == "filter_value" + assert response.most_recent_editor == "most_recent_editor_value" + assert response.type_ == gcs_mute_config.MuteConfig.MuteConfigType.STATIC + + +def test_update_mute_config_rest_required_fields( + request_type=securitycenter_service.UpdateMuteConfigRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_mute_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_mute_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_mute_config.MuteConfig() + # 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 = gcs_mute_config.MuteConfig.pb(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_mute_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_mute_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_mute_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("muteConfig",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_mute_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_update_mute_config" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_update_mute_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateMuteConfigRequest.pb( + securitycenter_service.UpdateMuteConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_mute_config.MuteConfig.to_json( + gcs_mute_config.MuteConfig() + ) + + request = securitycenter_service.UpdateMuteConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_mute_config.MuteConfig() + + client.update_mute_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_mute_config_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.UpdateMuteConfigRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "mute_config": {"name": "organizations/sample1/muteConfigs/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_mute_config(request) + + +def test_update_mute_config_rest_flattened(): + client = SecurityCenterClient( + 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 = gcs_mute_config.MuteConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "mute_config": {"name": "organizations/sample1/muteConfigs/sample2"} + } + + # get truthy value for each flattened field + mock_args = dict( + mute_config=gcs_mute_config.MuteConfig(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 = gcs_mute_config.MuteConfig.pb(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_mute_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/v2/{mute_config.name=organizations/*/muteConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_update_mute_config_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_mute_config( + securitycenter_service.UpdateMuteConfigRequest(), + mute_config=gcs_mute_config.MuteConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_mute_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.UpdateNotificationConfigRequest, + dict, + ], +) +def test_update_notification_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "notification_config": { + "name": "organizations/sample1/locations/sample2/notificationConfigs/sample3" + } + } + request_init["notification_config"] = { + "name": "organizations/sample1/locations/sample2/notificationConfigs/sample3", + "description": "description_value", + "pubsub_topic": "pubsub_topic_value", + "service_account": "service_account_value", + "streaming_config": {"filter": "filter_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 = securitycenter_service.UpdateNotificationConfigRequest.meta.fields[ + "notification_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["notification_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["notification_config"][field])): + del request_init["notification_config"][field][i][subfield] + else: + del request_init["notification_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 = gcs_notification_config.NotificationConfig( + name="name_value", + description="description_value", + pubsub_topic="pubsub_topic_value", + service_account="service_account_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 = gcs_notification_config.NotificationConfig.pb(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_notification_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.pubsub_topic == "pubsub_topic_value" + assert response.service_account == "service_account_value" + + +def test_update_notification_config_rest_required_fields( + request_type=securitycenter_service.UpdateNotificationConfigRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_notification_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_notification_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_notification_config.NotificationConfig() + # 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 = gcs_notification_config.NotificationConfig.pb(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_notification_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_notification_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_notification_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("notificationConfig",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_notification_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_update_notification_config" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_update_notification_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateNotificationConfigRequest.pb( + securitycenter_service.UpdateNotificationConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_notification_config.NotificationConfig.to_json( + gcs_notification_config.NotificationConfig() + ) + + request = securitycenter_service.UpdateNotificationConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_notification_config.NotificationConfig() + + client.update_notification_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_notification_config_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.UpdateNotificationConfigRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "notification_config": { + "name": "organizations/sample1/locations/sample2/notificationConfigs/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_notification_config(request) + + +def test_update_notification_config_rest_flattened(): + client = SecurityCenterClient( + 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 = gcs_notification_config.NotificationConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "notification_config": { + "name": "organizations/sample1/locations/sample2/notificationConfigs/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + notification_config=gcs_notification_config.NotificationConfig( + 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 = gcs_notification_config.NotificationConfig.pb(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_notification_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/v2/{notification_config.name=organizations/*/locations/*/notificationConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_update_notification_config_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_notification_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_notification_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.UpdateResourceValueConfigRequest, + dict, + ], +) +def test_update_resource_value_config_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "resource_value_config": { + "name": "organizations/sample1/resourceValueConfigs/sample2" + } + } + request_init["resource_value_config"] = { + "name": "organizations/sample1/resourceValueConfigs/sample2", + "resource_value": 1, + "tag_values": ["tag_values_value1", "tag_values_value2"], + "resource_type": "resource_type_value", + "scope": "scope_value", + "resource_labels_selector": {}, + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "sensitive_data_protection_mapping": { + "high_sensitivity_mapping": 1, + "medium_sensitivity_mapping": 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 = securitycenter_service.UpdateResourceValueConfigRequest.meta.fields[ + "resource_value_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[ + "resource_value_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["resource_value_config"][field])): + del request_init["resource_value_config"][field][i][subfield] + else: + del request_init["resource_value_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 = gcs_resource_value_config.ResourceValueConfig( + name="name_value", + resource_value=gcs_resource_value_config.ResourceValue.HIGH, + tag_values=["tag_values_value"], + resource_type="resource_type_value", + scope="scope_value", + description="description_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 = gcs_resource_value_config.ResourceValueConfig.pb(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_resource_value_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_resource_value_config.ResourceValueConfig) + assert response.name == "name_value" + assert response.resource_value == gcs_resource_value_config.ResourceValue.HIGH + assert response.tag_values == ["tag_values_value"] + assert response.resource_type == "resource_type_value" + assert response.scope == "scope_value" + assert response.description == "description_value" + + +def test_update_resource_value_config_rest_required_fields( + request_type=securitycenter_service.UpdateResourceValueConfigRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_resource_value_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_resource_value_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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_resource_value_config.ResourceValueConfig() + # 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 = gcs_resource_value_config.ResourceValueConfig.pb( + 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_resource_value_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_resource_value_config_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_resource_value_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("resourceValueConfig",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_resource_value_config_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_update_resource_value_config" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_update_resource_value_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateResourceValueConfigRequest.pb( + securitycenter_service.UpdateResourceValueConfigRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + gcs_resource_value_config.ResourceValueConfig.to_json( + gcs_resource_value_config.ResourceValueConfig() + ) + ) + + request = securitycenter_service.UpdateResourceValueConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_resource_value_config.ResourceValueConfig() + + client.update_resource_value_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_resource_value_config_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.UpdateResourceValueConfigRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "resource_value_config": { + "name": "organizations/sample1/resourceValueConfigs/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_resource_value_config(request) + + +def test_update_resource_value_config_rest_flattened(): + client = SecurityCenterClient( + 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 = gcs_resource_value_config.ResourceValueConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "resource_value_config": { + "name": "organizations/sample1/resourceValueConfigs/sample2" + } + } + + # get truthy value for each flattened field + mock_args = dict( + resource_value_config=gcs_resource_value_config.ResourceValueConfig( + 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 = gcs_resource_value_config.ResourceValueConfig.pb(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_resource_value_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/v2/{resource_value_config.name=organizations/*/resourceValueConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_update_resource_value_config_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_resource_value_config( + securitycenter_service.UpdateResourceValueConfigRequest(), + resource_value_config=gcs_resource_value_config.ResourceValueConfig( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_resource_value_config_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.UpdateSecurityMarksRequest, + dict, + ], +) +def test_update_security_marks_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "security_marks": { + "name": "organizations/sample1/sources/sample2/findings/sample3/securityMarks" + } + } + request_init["security_marks"] = { + "name": "organizations/sample1/sources/sample2/findings/sample3/securityMarks", + "marks": {}, + "canonical_name": "canonical_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 = securitycenter_service.UpdateSecurityMarksRequest.meta.fields[ + "security_marks" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["security_marks"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["security_marks"][field])): + del request_init["security_marks"][field][i][subfield] + else: + del request_init["security_marks"][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 = gcs_security_marks.SecurityMarks( + name="name_value", + canonical_name="canonical_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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == "name_value" + assert response.canonical_name == "canonical_name_value" + + +def test_update_security_marks_rest_required_fields( + request_type=securitycenter_service.UpdateSecurityMarksRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_security_marks._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_security_marks._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_security_marks.SecurityMarks() + # 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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_security_marks_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_security_marks._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("securityMarks",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_security_marks_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_update_security_marks" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_update_security_marks" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSecurityMarksRequest.pb( + securitycenter_service.UpdateSecurityMarksRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_security_marks.SecurityMarks.to_json( + gcs_security_marks.SecurityMarks() + ) + + request = securitycenter_service.UpdateSecurityMarksRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_security_marks.SecurityMarks() + + client.update_security_marks( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_security_marks_rest_bad_request( + transport: str = "rest", + request_type=securitycenter_service.UpdateSecurityMarksRequest, +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "security_marks": { + "name": "organizations/sample1/sources/sample2/findings/sample3/securityMarks" + } + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_security_marks(request) + + +def test_update_security_marks_rest_flattened(): + client = SecurityCenterClient( + 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 = gcs_security_marks.SecurityMarks() + + # get arguments that satisfy an http rule for this method + sample_request = { + "security_marks": { + "name": "organizations/sample1/sources/sample2/findings/sample3/securityMarks" + } + } + + # get truthy value for each flattened field + mock_args = dict( + security_marks=gcs_security_marks.SecurityMarks(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 = gcs_security_marks.SecurityMarks.pb(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_security_marks(**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/v2/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}" + % client.transport._host, + args[1], + ) + + +def test_update_security_marks_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_security_marks_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + securitycenter_service.UpdateSourceRequest, + dict, + ], +) +def test_update_source_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"source": {"name": "organizations/sample1/sources/sample2"}} + request_init["source"] = { + "name": "organizations/sample1/sources/sample2", + "display_name": "display_name_value", + "description": "description_value", + "canonical_name": "canonical_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 = securitycenter_service.UpdateSourceRequest.meta.fields["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["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["source"][field])): + del request_init["source"][field][i][subfield] + else: + del request_init["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 = gcs_source.Source( + name="name_value", + display_name="display_name_value", + description="description_value", + canonical_name="canonical_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 = gcs_source.Source.pb(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_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.canonical_name == "canonical_name_value" + + +def test_update_source_rest_required_fields( + request_type=securitycenter_service.UpdateSourceRequest, +): + transport_class = transports.SecurityCenterRestTransport + + 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_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_source._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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_source.Source() + # 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 = gcs_source.Source.pb(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_source(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_source_rest_unset_required_fields(): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_source._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("source",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_source_rest_interceptors(null_interceptor): + transport = transports.SecurityCenterRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecurityCenterRestInterceptor(), + ) + client = SecurityCenterClient(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.SecurityCenterRestInterceptor, "post_update_source" + ) as post, mock.patch.object( + transports.SecurityCenterRestInterceptor, "pre_update_source" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = securitycenter_service.UpdateSourceRequest.pb( + securitycenter_service.UpdateSourceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcs_source.Source.to_json(gcs_source.Source()) + + request = securitycenter_service.UpdateSourceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_source.Source() + + client.update_source( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_source_rest_bad_request( + transport: str = "rest", request_type=securitycenter_service.UpdateSourceRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"source": {"name": "organizations/sample1/sources/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_source(request) + + +def test_update_source_rest_flattened(): + client = SecurityCenterClient( + 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 = gcs_source.Source() + + # get arguments that satisfy an http rule for this method + sample_request = {"source": {"name": "organizations/sample1/sources/sample2"}} + + # get truthy value for each flattened field + mock_args = dict( + source=gcs_source.Source(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 = gcs_source.Source.pb(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_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/v2/{source.name=organizations/*/sources/*}" % client.transport._host, + args[1], + ) + + +def test_update_source_rest_flattened_error(transport: str = "rest"): + client = SecurityCenterClient( + 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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_source_rest_error(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SecurityCenterClient( + 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 = SecurityCenterClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SecurityCenterClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecurityCenterGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, + ], +) +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() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = SecurityCenterClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SecurityCenterGrpcTransport, + ) + + +def test_security_center_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_security_center_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.securitycenter_v2.services.security_center.transports.SecurityCenterTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "batch_create_resource_value_configs", + "bulk_mute_findings", + "create_big_query_export", + "create_finding", + "create_mute_config", + "create_notification_config", + "create_source", + "delete_big_query_export", + "delete_mute_config", + "delete_notification_config", + "delete_resource_value_config", + "get_big_query_export", + "get_simulation", + "get_valued_resource", + "get_iam_policy", + "get_mute_config", + "get_notification_config", + "get_resource_value_config", + "get_source", + "group_findings", + "list_attack_paths", + "list_big_query_exports", + "list_findings", + "list_mute_configs", + "list_notification_configs", + "list_resource_value_configs", + "list_sources", + "list_valued_resources", + "set_finding_state", + "set_iam_policy", + "set_mute", + "test_iam_permissions", + "update_big_query_export", + "update_external_system", + "update_finding", + "update_mute_config", + "update_notification_config", + "update_resource_value_config", + "update_security_marks", + "update_source", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_security_center_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.securitycenter_v2.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_security_center_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.securitycenter_v2.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport() + adc.assert_called_once() + + +def test_security_center_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SecurityCenterClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +def test_security_center_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + transports.SecurityCenterRestTransport, + ], +) +def test_security_center_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_security_center_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "securitycenter.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +def test_security_center_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_security_center_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.SecurityCenterRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_security_center_rest_lro_client(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_security_center_host_no_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="securitycenter.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "securitycenter.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://securitycenter.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_security_center_host_with_port(transport_name): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="securitycenter.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "securitycenter.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://securitycenter.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_security_center_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SecurityCenterClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SecurityCenterClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.batch_create_resource_value_configs._session + session2 = client2.transport.batch_create_resource_value_configs._session + assert session1 != session2 + session1 = client1.transport.bulk_mute_findings._session + session2 = client2.transport.bulk_mute_findings._session + assert session1 != session2 + session1 = client1.transport.create_big_query_export._session + session2 = client2.transport.create_big_query_export._session + assert session1 != session2 + session1 = client1.transport.create_finding._session + session2 = client2.transport.create_finding._session + assert session1 != session2 + session1 = client1.transport.create_mute_config._session + session2 = client2.transport.create_mute_config._session + assert session1 != session2 + session1 = client1.transport.create_notification_config._session + session2 = client2.transport.create_notification_config._session + assert session1 != session2 + session1 = client1.transport.create_source._session + session2 = client2.transport.create_source._session + assert session1 != session2 + session1 = client1.transport.delete_big_query_export._session + session2 = client2.transport.delete_big_query_export._session + assert session1 != session2 + session1 = client1.transport.delete_mute_config._session + session2 = client2.transport.delete_mute_config._session + assert session1 != session2 + session1 = client1.transport.delete_notification_config._session + session2 = client2.transport.delete_notification_config._session + assert session1 != session2 + session1 = client1.transport.delete_resource_value_config._session + session2 = client2.transport.delete_resource_value_config._session + assert session1 != session2 + session1 = client1.transport.get_big_query_export._session + session2 = client2.transport.get_big_query_export._session + assert session1 != session2 + session1 = client1.transport.get_simulation._session + session2 = client2.transport.get_simulation._session + assert session1 != session2 + session1 = client1.transport.get_valued_resource._session + session2 = client2.transport.get_valued_resource._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.get_mute_config._session + session2 = client2.transport.get_mute_config._session + assert session1 != session2 + session1 = client1.transport.get_notification_config._session + session2 = client2.transport.get_notification_config._session + assert session1 != session2 + session1 = client1.transport.get_resource_value_config._session + session2 = client2.transport.get_resource_value_config._session + assert session1 != session2 + session1 = client1.transport.get_source._session + session2 = client2.transport.get_source._session + assert session1 != session2 + session1 = client1.transport.group_findings._session + session2 = client2.transport.group_findings._session + assert session1 != session2 + session1 = client1.transport.list_attack_paths._session + session2 = client2.transport.list_attack_paths._session + assert session1 != session2 + session1 = client1.transport.list_big_query_exports._session + session2 = client2.transport.list_big_query_exports._session + assert session1 != session2 + session1 = client1.transport.list_findings._session + session2 = client2.transport.list_findings._session + assert session1 != session2 + session1 = client1.transport.list_mute_configs._session + session2 = client2.transport.list_mute_configs._session + assert session1 != session2 + session1 = client1.transport.list_notification_configs._session + session2 = client2.transport.list_notification_configs._session + assert session1 != session2 + session1 = client1.transport.list_resource_value_configs._session + session2 = client2.transport.list_resource_value_configs._session + assert session1 != session2 + session1 = client1.transport.list_sources._session + session2 = client2.transport.list_sources._session + assert session1 != session2 + session1 = client1.transport.list_valued_resources._session + session2 = client2.transport.list_valued_resources._session + assert session1 != session2 + session1 = client1.transport.set_finding_state._session + session2 = client2.transport.set_finding_state._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.set_mute._session + session2 = client2.transport.set_mute._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 + session1 = client1.transport.update_big_query_export._session + session2 = client2.transport.update_big_query_export._session + assert session1 != session2 + session1 = client1.transport.update_external_system._session + session2 = client2.transport.update_external_system._session + assert session1 != session2 + session1 = client1.transport.update_finding._session + session2 = client2.transport.update_finding._session + assert session1 != session2 + session1 = client1.transport.update_mute_config._session + session2 = client2.transport.update_mute_config._session + assert session1 != session2 + session1 = client1.transport.update_notification_config._session + session2 = client2.transport.update_notification_config._session + assert session1 != session2 + session1 = client1.transport.update_resource_value_config._session + session2 = client2.transport.update_resource_value_config._session + assert session1 != session2 + session1 = client1.transport.update_security_marks._session + session2 = client2.transport.update_security_marks._session + assert session1 != session2 + session1 = client1.transport.update_source._session + session2 = client2.transport.update_source._session + assert session1 != session2 + + +def test_security_center_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_security_center_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +def test_security_center_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +def test_security_center_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_security_center_grpc_lro_client(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_security_center_grpc_lro_async_client(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_attack_path_path(): + organization = "squid" + simulation = "clam" + valued_resource = "whelk" + attack_path = "octopus" + expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}/attackPaths/{attack_path}".format( + organization=organization, + simulation=simulation, + valued_resource=valued_resource, + attack_path=attack_path, + ) + actual = SecurityCenterClient.attack_path_path( + organization, simulation, valued_resource, attack_path + ) + assert expected == actual + + +def test_parse_attack_path_path(): + expected = { + "organization": "oyster", + "simulation": "nudibranch", + "valued_resource": "cuttlefish", + "attack_path": "mussel", + } + path = SecurityCenterClient.attack_path_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_attack_path_path(path) + assert expected == actual + + +def test_big_query_export_path(): + organization = "winkle" + location = "nautilus" + export = "scallop" + expected = "organizations/{organization}/locations/{location}/bigQueryExports/{export}".format( + organization=organization, + location=location, + export=export, + ) + actual = SecurityCenterClient.big_query_export_path(organization, location, export) + assert expected == actual + + +def test_parse_big_query_export_path(): + expected = { + "organization": "abalone", + "location": "squid", + "export": "clam", + } + path = SecurityCenterClient.big_query_export_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_big_query_export_path(path) + assert expected == actual + + +def test_dlp_job_path(): + project = "whelk" + dlp_job = "octopus" + expected = "projects/{project}/dlpJobs/{dlp_job}".format( + project=project, + dlp_job=dlp_job, + ) + actual = SecurityCenterClient.dlp_job_path(project, dlp_job) + assert expected == actual + + +def test_parse_dlp_job_path(): + expected = { + "project": "oyster", + "dlp_job": "nudibranch", + } + path = SecurityCenterClient.dlp_job_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_dlp_job_path(path) + assert expected == actual + + +def test_external_system_path(): + organization = "cuttlefish" + source = "mussel" + finding = "winkle" + externalsystem = "nautilus" + expected = "organizations/{organization}/sources/{source}/findings/{finding}/externalSystems/{externalsystem}".format( + organization=organization, + source=source, + finding=finding, + externalsystem=externalsystem, + ) + actual = SecurityCenterClient.external_system_path( + organization, source, finding, externalsystem + ) + assert expected == actual + + +def test_parse_external_system_path(): + expected = { + "organization": "scallop", + "source": "abalone", + "finding": "squid", + "externalsystem": "clam", + } + path = SecurityCenterClient.external_system_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_external_system_path(path) + assert expected == actual + + +def test_finding_path(): + organization = "whelk" + source = "octopus" + finding = "oyster" + expected = ( + "organizations/{organization}/sources/{source}/findings/{finding}".format( + organization=organization, + source=source, + finding=finding, + ) + ) + actual = SecurityCenterClient.finding_path(organization, source, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "organization": "nudibranch", + "source": "cuttlefish", + "finding": "mussel", + } + path = SecurityCenterClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_finding_path(path) + assert expected == actual + + +def test_mute_config_path(): + organization = "winkle" + mute_config = "nautilus" + expected = "organizations/{organization}/muteConfigs/{mute_config}".format( + organization=organization, + mute_config=mute_config, + ) + actual = SecurityCenterClient.mute_config_path(organization, mute_config) + assert expected == actual + + +def test_parse_mute_config_path(): + expected = { + "organization": "scallop", + "mute_config": "abalone", + } + path = SecurityCenterClient.mute_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_mute_config_path(path) + assert expected == actual + + +def test_notification_config_path(): + organization = "squid" + location = "clam" + notification_config = "whelk" + expected = "organizations/{organization}/locations/{location}/notificationConfigs/{notification_config}".format( + organization=organization, + location=location, + notification_config=notification_config, + ) + actual = SecurityCenterClient.notification_config_path( + organization, location, notification_config + ) + assert expected == actual + + +def test_parse_notification_config_path(): + expected = { + "organization": "octopus", + "location": "oyster", + "notification_config": "nudibranch", + } + path = SecurityCenterClient.notification_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_notification_config_path(path) + assert expected == actual + + +def test_policy_path(): + organization = "cuttlefish" + constraint_name = "mussel" + expected = "organizations/{organization}/policies/{constraint_name}".format( + organization=organization, + constraint_name=constraint_name, + ) + actual = SecurityCenterClient.policy_path(organization, constraint_name) + assert expected == actual + + +def test_parse_policy_path(): + expected = { + "organization": "winkle", + "constraint_name": "nautilus", + } + path = SecurityCenterClient.policy_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_policy_path(path) + assert expected == actual + + +def test_resource_value_config_path(): + organization = "scallop" + resource_value_config = "abalone" + expected = "organizations/{organization}/resourceValueConfigs/{resource_value_config}".format( + organization=organization, + resource_value_config=resource_value_config, + ) + actual = SecurityCenterClient.resource_value_config_path( + organization, resource_value_config + ) + assert expected == actual + + +def test_parse_resource_value_config_path(): + expected = { + "organization": "squid", + "resource_value_config": "clam", + } + path = SecurityCenterClient.resource_value_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_resource_value_config_path(path) + assert expected == actual + + +def test_security_marks_path(): + organization = "whelk" + asset = "octopus" + expected = "organizations/{organization}/assets/{asset}/securityMarks".format( + organization=organization, + asset=asset, + ) + actual = SecurityCenterClient.security_marks_path(organization, asset) + assert expected == actual + + +def test_parse_security_marks_path(): + expected = { + "organization": "oyster", + "asset": "nudibranch", + } + path = SecurityCenterClient.security_marks_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_security_marks_path(path) + assert expected == actual + + +def test_simulation_path(): + organization = "cuttlefish" + simulation = "mussel" + expected = "organizations/{organization}/simulations/{simulation}".format( + organization=organization, + simulation=simulation, + ) + actual = SecurityCenterClient.simulation_path(organization, simulation) + assert expected == actual + + +def test_parse_simulation_path(): + expected = { + "organization": "winkle", + "simulation": "nautilus", + } + path = SecurityCenterClient.simulation_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_simulation_path(path) + assert expected == actual + + +def test_source_path(): + organization = "scallop" + source = "abalone" + expected = "organizations/{organization}/sources/{source}".format( + organization=organization, + source=source, + ) + actual = SecurityCenterClient.source_path(organization, source) + assert expected == actual + + +def test_parse_source_path(): + expected = { + "organization": "squid", + "source": "clam", + } + path = SecurityCenterClient.source_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_source_path(path) + assert expected == actual + + +def test_table_data_profile_path(): + project = "whelk" + table_profile = "octopus" + expected = "projects/{project}/tableProfiles/{table_profile}".format( + project=project, + table_profile=table_profile, + ) + actual = SecurityCenterClient.table_data_profile_path(project, table_profile) + assert expected == actual + + +def test_parse_table_data_profile_path(): + expected = { + "project": "oyster", + "table_profile": "nudibranch", + } + path = SecurityCenterClient.table_data_profile_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_table_data_profile_path(path) + assert expected == actual + + +def test_topic_path(): + project = "cuttlefish" + topic = "mussel" + expected = "projects/{project}/topics/{topic}".format( + project=project, + topic=topic, + ) + actual = SecurityCenterClient.topic_path(project, topic) + assert expected == actual + + +def test_parse_topic_path(): + expected = { + "project": "winkle", + "topic": "nautilus", + } + path = SecurityCenterClient.topic_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_topic_path(path) + assert expected == actual + + +def test_valued_resource_path(): + organization = "scallop" + simulation = "abalone" + valued_resource = "squid" + expected = "organizations/{organization}/simulations/{simulation}/valuedResources/{valued_resource}".format( + organization=organization, + simulation=simulation, + valued_resource=valued_resource, + ) + actual = SecurityCenterClient.valued_resource_path( + organization, simulation, valued_resource + ) + assert expected == actual + + +def test_parse_valued_resource_path(): + expected = { + "organization": "clam", + "simulation": "whelk", + "valued_resource": "octopus", + } + path = SecurityCenterClient.valued_resource_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_valued_resource_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = SecurityCenterClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = SecurityCenterClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = SecurityCenterClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = SecurityCenterClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = SecurityCenterClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = SecurityCenterClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format( + project=project, + ) + actual = SecurityCenterClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = SecurityCenterClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = SecurityCenterClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = SecurityCenterClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.SecurityCenterTransport, "_prep_wrapped_messages" + ) as prep: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.SecurityCenterTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = SecurityCenterClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_cancel_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.CancelOperationRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "organizations/sample1/operations/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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "organizations/sample1/operations/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.DeleteOperationRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "organizations/sample1/operations/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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "organizations/sample1/operations/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "{}" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + 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( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "organizations/sample1/operations/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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "organizations/sample1/operations/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 = operations_pb2.Operation() + + # 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 + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.ListOperationsRequest +): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "organizations/sample1/operations"}, 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "organizations/sample1/operations"} + 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.ListOperationsResponse() + + # 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 + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = SecurityCenterClient( + 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 = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(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 response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + 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 = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(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 response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = SecurityCenterClient( + 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 = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(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=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(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=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = SecurityCenterClient( + 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 = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(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 response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + 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 = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(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 response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = SecurityCenterClient( + 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 = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(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=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(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=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = SecurityCenterClient( + 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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(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 response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + 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 = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(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 response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = SecurityCenterClient( + 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 = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(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=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(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=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = SecurityCenterClient( + 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 = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(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 response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + 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 = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(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 response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = SecurityCenterClient( + 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 = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(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=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = SecurityCenterAsyncClient( + 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 = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(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=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-securitycentermanagement/CHANGELOG.md b/packages/google-cloud-securitycentermanagement/CHANGELOG.md index 5463da185d82..eb6fcfb4ffb6 100644 --- a/packages/google-cloud-securitycentermanagement/CHANGELOG.md +++ b/packages/google-cloud-securitycentermanagement/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## [0.1.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-securitycentermanagement-v0.1.6...google-cloud-securitycentermanagement-v0.1.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([add6a6d](https://github.com/googleapis/google-cloud-python/commit/add6a6d5198c81e35e5edf8997eb9fde2cc9c81b)) + + +### Documentation + +* Clarify documentation for ListDescendantSecurityHealthAnalyticsCustomModules RPC and CustomConfig message ([add6a6d](https://github.com/googleapis/google-cloud-python/commit/add6a6d5198c81e35e5edf8997eb9fde2cc9c81b)) + ## [0.1.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-securitycentermanagement-v0.1.5...google-cloud-securitycentermanagement-v0.1.6) (2024-02-22) 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 60402a4567d1..e34e491c76d0 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.6" # {x-release-please-version} +__version__ = "0.1.7" # {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 60402a4567d1..e34e491c76d0 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.6" # {x-release-please-version} +__version__ = "0.1.7" # {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 19fe68d2a63f..a8a7bc870e13 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 @@ -737,7 +737,7 @@ async def list_descendant_security_health_analytics_custom_modules( ) -> pagers.ListDescendantSecurityHealthAnalyticsCustomModulesAsyncPager: r"""Returns a list of all resident SecurityHealthAnalyticsCustomModules under the given CRM - parent and all of the parent’s CRM descendants. + parent and all of the parent's CRM descendants. .. code-block:: python 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 48a663fc3e1f..615507391a27 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 @@ -1200,7 +1200,7 @@ def list_descendant_security_health_analytics_custom_modules( ) -> pagers.ListDescendantSecurityHealthAnalyticsCustomModulesPager: r"""Returns a list of all resident SecurityHealthAnalyticsCustomModules under the given CRM - parent and all of the parent’s CRM descendants. + parent and all of the parent's CRM descendants. .. code-block:: python 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 fae3f7e01eca..84f6ed8e127a 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 @@ -353,7 +353,7 @@ def list_descendant_security_health_analytics_custom_modules( Returns a list of all resident SecurityHealthAnalyticsCustomModules under the given CRM - parent and all of the parent’s CRM descendants. + parent and all of the parent's CRM descendants. Returns: Callable[[~.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], 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 14cffc445dc7..16097dc80707 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 @@ -364,7 +364,7 @@ def list_descendant_security_health_analytics_custom_modules( Returns a list of all resident SecurityHealthAnalyticsCustomModules under the given CRM - parent and all of the parent’s CRM descendants. + parent and all of the parent's CRM descendants. Returns: Callable[[~.ListDescendantSecurityHealthAnalyticsCustomModulesRequest], 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 149dff52364f..e5f5aec906d2 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 @@ -346,11 +346,11 @@ class CustomConfig(proto.Message): custom_output (google.cloud.securitycentermanagement_v1.types.CustomConfig.CustomOutputSpec): Optional. Custom output properties. resource_selector (google.cloud.securitycentermanagement_v1.types.CustomConfig.ResourceSelector): - Optional. The CAI resource types that the - custom module operates on (see - go/gcp-cai-doc/supported-asset-types). Each - custom module can specify up to 5 resource - types. + Optional. The Cloud Asset Inventory resource types that the + custom module operates on. For information about resource + types, see `Supported asset + types `__. + Each custom module can specify up to 5 resource types. severity (google.cloud.securitycentermanagement_v1.types.CustomConfig.Severity): Optional. The severity to assign to findings generated by the module. 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 bb10af571156..79bf38758f28 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.6" + "version": "0.1.7" }, "snippets": [ { diff --git a/packages/google-cloud-securitycentermanagement/setup.py b/packages/google-cloud-securitycentermanagement/setup.py index c9b62126a1f9..d12693d4605a 100644 --- a/packages/google-cloud-securitycentermanagement/setup.py +++ b/packages/google-cloud-securitycentermanagement/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-service-control/CHANGELOG.md b/packages/google-cloud-service-control/CHANGELOG.md index 2029e8115306..7f92f96613be 100644 --- a/packages/google-cloud-service-control/CHANGELOG.md +++ b/packages/google-cloud-service-control/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.12.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-service-control-v1.12.0...google-cloud-service-control-v1.12.1) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [1.12.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-service-control-v1.11.1...google-cloud-service-control-v1.12.0) (2024-02-22) 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 18a7732658ee..ac3bc60c3fb3 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.12.0" # {x-release-please-version} +__version__ = "1.12.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 18a7732658ee..ac3bc60c3fb3 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.12.0" # {x-release-please-version} +__version__ = "1.12.1" # {x-release-please-version} 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 18a7732658ee..ac3bc60c3fb3 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.12.0" # {x-release-please-version} +__version__ = "1.12.1" # {x-release-please-version} 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 4b6f68b94148..ca84f02cbfd1 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.12.0" + "version": "1.12.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 e193f7cd7e15..22b01b022560 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.12.0" + "version": "1.12.1" }, "snippets": [ { diff --git a/packages/google-cloud-service-control/setup.py b/packages/google-cloud-service-control/setup.py index 4b3afd2d7ab4..094684946f9d 100644 --- a/packages/google-cloud-service-control/setup.py +++ b/packages/google-cloud-service-control/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-service-directory/CHANGELOG.md b/packages/google-cloud-service-directory/CHANGELOG.md index 9e9cc9b6d479..50171a572ca8 100644 --- a/packages/google-cloud-service-directory/CHANGELOG.md +++ b/packages/google-cloud-service-directory/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.11.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-service-directory-v1.11.2...google-cloud-service-directory-v1.11.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [1.11.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-service-directory-v1.11.1...google-cloud-service-directory-v1.11.2) (2024-02-22) diff --git a/packages/google-cloud-service-directory/google/cloud/servicedirectory/gapic_version.py b/packages/google-cloud-service-directory/google/cloud/servicedirectory/gapic_version.py index 787a045996f3..88fbabfeb794 100644 --- a/packages/google-cloud-service-directory/google/cloud/servicedirectory/gapic_version.py +++ b/packages/google-cloud-service-directory/google/cloud/servicedirectory/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.11.2" # {x-release-please-version} +__version__ = "1.11.3" # {x-release-please-version} diff --git a/packages/google-cloud-service-directory/google/cloud/servicedirectory_v1/gapic_version.py b/packages/google-cloud-service-directory/google/cloud/servicedirectory_v1/gapic_version.py index 787a045996f3..88fbabfeb794 100644 --- a/packages/google-cloud-service-directory/google/cloud/servicedirectory_v1/gapic_version.py +++ b/packages/google-cloud-service-directory/google/cloud/servicedirectory_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.2" # {x-release-please-version} +__version__ = "1.11.3" # {x-release-please-version} diff --git a/packages/google-cloud-service-directory/google/cloud/servicedirectory_v1beta1/gapic_version.py b/packages/google-cloud-service-directory/google/cloud/servicedirectory_v1beta1/gapic_version.py index 787a045996f3..88fbabfeb794 100644 --- a/packages/google-cloud-service-directory/google/cloud/servicedirectory_v1beta1/gapic_version.py +++ b/packages/google-cloud-service-directory/google/cloud/servicedirectory_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.2" # {x-release-please-version} +__version__ = "1.11.3" # {x-release-please-version} diff --git a/packages/google-cloud-service-directory/samples/generated_samples/snippet_metadata_google.cloud.servicedirectory.v1.json b/packages/google-cloud-service-directory/samples/generated_samples/snippet_metadata_google.cloud.servicedirectory.v1.json index ffcb0923635f..d2fa62091490 100644 --- a/packages/google-cloud-service-directory/samples/generated_samples/snippet_metadata_google.cloud.servicedirectory.v1.json +++ b/packages/google-cloud-service-directory/samples/generated_samples/snippet_metadata_google.cloud.servicedirectory.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-service-directory", - "version": "1.11.2" + "version": "1.11.3" }, "snippets": [ { diff --git a/packages/google-cloud-service-directory/samples/generated_samples/snippet_metadata_google.cloud.servicedirectory.v1beta1.json b/packages/google-cloud-service-directory/samples/generated_samples/snippet_metadata_google.cloud.servicedirectory.v1beta1.json index cc859961cac6..259aa1db00bd 100644 --- a/packages/google-cloud-service-directory/samples/generated_samples/snippet_metadata_google.cloud.servicedirectory.v1beta1.json +++ b/packages/google-cloud-service-directory/samples/generated_samples/snippet_metadata_google.cloud.servicedirectory.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-service-directory", - "version": "1.11.2" + "version": "1.11.3" }, "snippets": [ { diff --git a/packages/google-cloud-service-directory/setup.py b/packages/google-cloud-service-directory/setup.py index 0a61843c9842..e6a8884121d5 100644 --- a/packages/google-cloud-service-directory/setup.py +++ b/packages/google-cloud-service-directory/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-service-management/CHANGELOG.md b/packages/google-cloud-service-management/CHANGELOG.md index ea6cbeecfe54..4d4f72a843e0 100644 --- a/packages/google-cloud-service-management/CHANGELOG.md +++ b/packages/google-cloud-service-management/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.8.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-service-management-v1.8.2...google-cloud-service-management-v1.8.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [1.8.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-service-management-v1.8.1...google-cloud-service-management-v1.8.2) (2024-02-22) 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 0b81cd44c284..f9e85c87b4d6 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.8.2" # {x-release-please-version} +__version__ = "1.8.3" # {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 0b81cd44c284..f9e85c87b4d6 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.8.2" # {x-release-please-version} +__version__ = "1.8.3" # {x-release-please-version} 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 3dfb3d0c5a43..2e66b4e5405e 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.8.2" + "version": "1.8.3" }, "snippets": [ { diff --git a/packages/google-cloud-service-management/setup.py b/packages/google-cloud-service-management/setup.py index 5eb5cda5df4e..8aa27bca95ca 100644 --- a/packages/google-cloud-service-management/setup.py +++ b/packages/google-cloud-service-management/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-service-usage/CHANGELOG.md b/packages/google-cloud-service-usage/CHANGELOG.md index 17bc2a6fea6d..4c8ea2190be9 100644 --- a/packages/google-cloud-service-usage/CHANGELOG.md +++ b/packages/google-cloud-service-usage/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.10.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-service-usage-v1.10.2...google-cloud-service-usage-v1.10.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [1.10.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-service-usage-v1.10.1...google-cloud-service-usage-v1.10.2) (2024-02-22) 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 7a033a50e6cd..d74c07c1961e 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.10.2" # {x-release-please-version} +__version__ = "1.10.3" # {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 7a033a50e6cd..d74c07c1961e 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.10.2" # {x-release-please-version} +__version__ = "1.10.3" # {x-release-please-version} 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 2d92900cb081..454d49543392 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.10.2" + "version": "1.10.3" }, "snippets": [ { diff --git a/packages/google-cloud-service-usage/setup.py b/packages/google-cloud-service-usage/setup.py index 37dd69c7b556..2632313ec8d4 100644 --- a/packages/google-cloud-service-usage/setup.py +++ b/packages/google-cloud-service-usage/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-servicehealth/CHANGELOG.md b/packages/google-cloud-servicehealth/CHANGELOG.md index ba68a0767e31..8bbedaf9f6f7 100644 --- a/packages/google-cloud-servicehealth/CHANGELOG.md +++ b/packages/google-cloud-servicehealth/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.4](https://github.com/googleapis/google-cloud-python/compare/google-cloud-servicehealth-v0.1.3...google-cloud-servicehealth-v0.1.4) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [0.1.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-servicehealth-v0.1.2...google-cloud-servicehealth-v0.1.3) (2024-02-22) diff --git a/packages/google-cloud-servicehealth/google/cloud/servicehealth/gapic_version.py b/packages/google-cloud-servicehealth/google/cloud/servicehealth/gapic_version.py index 536d6648a6f0..286ce4ad5531 100644 --- a/packages/google-cloud-servicehealth/google/cloud/servicehealth/gapic_version.py +++ b/packages/google-cloud-servicehealth/google/cloud/servicehealth/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-servicehealth/google/cloud/servicehealth_v1/gapic_version.py b/packages/google-cloud-servicehealth/google/cloud/servicehealth_v1/gapic_version.py index 536d6648a6f0..286ce4ad5531 100644 --- a/packages/google-cloud-servicehealth/google/cloud/servicehealth_v1/gapic_version.py +++ b/packages/google-cloud-servicehealth/google/cloud/servicehealth_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-servicehealth/samples/generated_samples/snippet_metadata_google.cloud.servicehealth.v1.json b/packages/google-cloud-servicehealth/samples/generated_samples/snippet_metadata_google.cloud.servicehealth.v1.json index 553e647738d1..04c12c254882 100644 --- a/packages/google-cloud-servicehealth/samples/generated_samples/snippet_metadata_google.cloud.servicehealth.v1.json +++ b/packages/google-cloud-servicehealth/samples/generated_samples/snippet_metadata_google.cloud.servicehealth.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-servicehealth", - "version": "0.1.3" + "version": "0.1.4" }, "snippets": [ { diff --git a/packages/google-cloud-servicehealth/setup.py b/packages/google-cloud-servicehealth/setup.py index a5962574e1d3..1ef163642035 100644 --- a/packages/google-cloud-servicehealth/setup.py +++ b/packages/google-cloud-servicehealth/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-shell/CHANGELOG.md b/packages/google-cloud-shell/CHANGELOG.md index babff16aa063..6a89966a8dd3 100644 --- a/packages/google-cloud-shell/CHANGELOG.md +++ b/packages/google-cloud-shell/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.9.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-shell-v1.9.2...google-cloud-shell-v1.9.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [1.9.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-shell-v1.9.1...google-cloud-shell-v1.9.2) (2024-02-22) diff --git a/packages/google-cloud-shell/google/cloud/shell/gapic_version.py b/packages/google-cloud-shell/google/cloud/shell/gapic_version.py index f14078b6f555..ec42a8e289c4 100644 --- a/packages/google-cloud-shell/google/cloud/shell/gapic_version.py +++ b/packages/google-cloud-shell/google/cloud/shell/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} diff --git a/packages/google-cloud-shell/google/cloud/shell_v1/gapic_version.py b/packages/google-cloud-shell/google/cloud/shell_v1/gapic_version.py index f14078b6f555..ec42a8e289c4 100644 --- a/packages/google-cloud-shell/google/cloud/shell_v1/gapic_version.py +++ b/packages/google-cloud-shell/google/cloud/shell_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} diff --git a/packages/google-cloud-shell/samples/generated_samples/snippet_metadata_google.cloud.shell.v1.json b/packages/google-cloud-shell/samples/generated_samples/snippet_metadata_google.cloud.shell.v1.json index 0cea08bf6b02..db50371a69a4 100644 --- a/packages/google-cloud-shell/samples/generated_samples/snippet_metadata_google.cloud.shell.v1.json +++ b/packages/google-cloud-shell/samples/generated_samples/snippet_metadata_google.cloud.shell.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-shell", - "version": "1.9.2" + "version": "1.9.3" }, "snippets": [ { diff --git a/packages/google-cloud-shell/setup.py b/packages/google-cloud-shell/setup.py index d9e443a9a335..3092b86ccd38 100644 --- a/packages/google-cloud-shell/setup.py +++ b/packages/google-cloud-shell/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-source-context/CHANGELOG.md b/packages/google-cloud-source-context/CHANGELOG.md index b5b7b9435c11..4cd1be19257e 100644 --- a/packages/google-cloud-source-context/CHANGELOG.md +++ b/packages/google-cloud-source-context/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.5.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-source-context-v1.5.2...google-cloud-source-context-v1.5.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [1.5.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-source-context-v1.5.1...google-cloud-source-context-v1.5.2) (2024-02-22) diff --git a/packages/google-cloud-source-context/google/cloud/source_context/gapic_version.py b/packages/google-cloud-source-context/google/cloud/source_context/gapic_version.py index 01f1b9735dc4..21964d6e5abf 100644 --- a/packages/google-cloud-source-context/google/cloud/source_context/gapic_version.py +++ b/packages/google-cloud-source-context/google/cloud/source_context/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.5.2" # {x-release-please-version} +__version__ = "1.5.3" # {x-release-please-version} diff --git a/packages/google-cloud-source-context/google/cloud/source_context_v1/gapic_version.py b/packages/google-cloud-source-context/google/cloud/source_context_v1/gapic_version.py index 01f1b9735dc4..21964d6e5abf 100644 --- a/packages/google-cloud-source-context/google/cloud/source_context_v1/gapic_version.py +++ b/packages/google-cloud-source-context/google/cloud/source_context_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.5.2" # {x-release-please-version} +__version__ = "1.5.3" # {x-release-please-version} diff --git a/packages/google-cloud-source-context/setup.py b/packages/google-cloud-source-context/setup.py index 6a3b65043c62..c2e48ce2d002 100644 --- a/packages/google-cloud-source-context/setup.py +++ b/packages/google-cloud-source-context/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-speech/CHANGELOG.md b/packages/google-cloud-speech/CHANGELOG.md index 8943ee243361..4440183c44b1 100644 --- a/packages/google-cloud-speech/CHANGELOG.md +++ b/packages/google-cloud-speech/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-speech/#history +## [2.25.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-speech-v2.25.0...google-cloud-speech-v2.25.1) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [2.25.0](https://github.com/googleapis/google-cloud-python/compare/google-cloud-speech-v2.24.1...google-cloud-speech-v2.25.0) (2024-02-22) diff --git a/packages/google-cloud-speech/google/cloud/speech/gapic_version.py b/packages/google-cloud-speech/google/cloud/speech/gapic_version.py index 2c668c3896ae..5b8910a6beb4 100644 --- a/packages/google-cloud-speech/google/cloud/speech/gapic_version.py +++ b/packages/google-cloud-speech/google/cloud/speech/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.25.0" # {x-release-please-version} +__version__ = "2.25.1" # {x-release-please-version} diff --git a/packages/google-cloud-speech/google/cloud/speech_v1/gapic_version.py b/packages/google-cloud-speech/google/cloud/speech_v1/gapic_version.py index 2c668c3896ae..5b8910a6beb4 100644 --- a/packages/google-cloud-speech/google/cloud/speech_v1/gapic_version.py +++ b/packages/google-cloud-speech/google/cloud/speech_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.25.0" # {x-release-please-version} +__version__ = "2.25.1" # {x-release-please-version} diff --git a/packages/google-cloud-speech/google/cloud/speech_v1p1beta1/gapic_version.py b/packages/google-cloud-speech/google/cloud/speech_v1p1beta1/gapic_version.py index 2c668c3896ae..5b8910a6beb4 100644 --- a/packages/google-cloud-speech/google/cloud/speech_v1p1beta1/gapic_version.py +++ b/packages/google-cloud-speech/google/cloud/speech_v1p1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.25.0" # {x-release-please-version} +__version__ = "2.25.1" # {x-release-please-version} diff --git a/packages/google-cloud-speech/google/cloud/speech_v2/gapic_version.py b/packages/google-cloud-speech/google/cloud/speech_v2/gapic_version.py index 2c668c3896ae..5b8910a6beb4 100644 --- a/packages/google-cloud-speech/google/cloud/speech_v2/gapic_version.py +++ b/packages/google-cloud-speech/google/cloud/speech_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.25.0" # {x-release-please-version} +__version__ = "2.25.1" # {x-release-please-version} diff --git a/packages/google-cloud-speech/samples/generated_samples/snippet_metadata_google.cloud.speech.v1.json b/packages/google-cloud-speech/samples/generated_samples/snippet_metadata_google.cloud.speech.v1.json index 0ea37d398448..2964f355d2e4 100644 --- a/packages/google-cloud-speech/samples/generated_samples/snippet_metadata_google.cloud.speech.v1.json +++ b/packages/google-cloud-speech/samples/generated_samples/snippet_metadata_google.cloud.speech.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-speech", - "version": "2.25.0" + "version": "2.25.1" }, "snippets": [ { diff --git a/packages/google-cloud-speech/samples/generated_samples/snippet_metadata_google.cloud.speech.v1p1beta1.json b/packages/google-cloud-speech/samples/generated_samples/snippet_metadata_google.cloud.speech.v1p1beta1.json index 538f69902a53..b907a1748a7e 100644 --- a/packages/google-cloud-speech/samples/generated_samples/snippet_metadata_google.cloud.speech.v1p1beta1.json +++ b/packages/google-cloud-speech/samples/generated_samples/snippet_metadata_google.cloud.speech.v1p1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-speech", - "version": "2.25.0" + "version": "2.25.1" }, "snippets": [ { diff --git a/packages/google-cloud-speech/samples/generated_samples/snippet_metadata_google.cloud.speech.v2.json b/packages/google-cloud-speech/samples/generated_samples/snippet_metadata_google.cloud.speech.v2.json index e24454186252..493cdb394566 100644 --- a/packages/google-cloud-speech/samples/generated_samples/snippet_metadata_google.cloud.speech.v2.json +++ b/packages/google-cloud-speech/samples/generated_samples/snippet_metadata_google.cloud.speech.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-speech", - "version": "2.25.0" + "version": "2.25.1" }, "snippets": [ { diff --git a/packages/google-cloud-speech/setup.py b/packages/google-cloud-speech/setup.py index 207a3f623076..43b9c68d1bf7 100644 --- a/packages/google-cloud-speech/setup.py +++ b/packages/google-cloud-speech/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-storage-transfer/CHANGELOG.md b/packages/google-cloud-storage-transfer/CHANGELOG.md index b8a1667c8dbd..ac031b932c4c 100644 --- a/packages/google-cloud-storage-transfer/CHANGELOG.md +++ b/packages/google-cloud-storage-transfer/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.11.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-storage-transfer-v1.11.2...google-cloud-storage-transfer-v1.11.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [1.11.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-storage-transfer-v1.11.1...google-cloud-storage-transfer-v1.11.2) (2024-02-22) diff --git a/packages/google-cloud-storage-transfer/google/cloud/storage_transfer/gapic_version.py b/packages/google-cloud-storage-transfer/google/cloud/storage_transfer/gapic_version.py index 787a045996f3..88fbabfeb794 100644 --- a/packages/google-cloud-storage-transfer/google/cloud/storage_transfer/gapic_version.py +++ b/packages/google-cloud-storage-transfer/google/cloud/storage_transfer/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.11.2" # {x-release-please-version} +__version__ = "1.11.3" # {x-release-please-version} diff --git a/packages/google-cloud-storage-transfer/google/cloud/storage_transfer_v1/gapic_version.py b/packages/google-cloud-storage-transfer/google/cloud/storage_transfer_v1/gapic_version.py index 787a045996f3..88fbabfeb794 100644 --- a/packages/google-cloud-storage-transfer/google/cloud/storage_transfer_v1/gapic_version.py +++ b/packages/google-cloud-storage-transfer/google/cloud/storage_transfer_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.2" # {x-release-please-version} +__version__ = "1.11.3" # {x-release-please-version} diff --git a/packages/google-cloud-storage-transfer/samples/generated_samples/snippet_metadata_google.storagetransfer.v1.json b/packages/google-cloud-storage-transfer/samples/generated_samples/snippet_metadata_google.storagetransfer.v1.json index 7df88770b3ac..d0eb2fa3c269 100644 --- a/packages/google-cloud-storage-transfer/samples/generated_samples/snippet_metadata_google.storagetransfer.v1.json +++ b/packages/google-cloud-storage-transfer/samples/generated_samples/snippet_metadata_google.storagetransfer.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-storage-transfer", - "version": "1.11.2" + "version": "1.11.3" }, "snippets": [ { diff --git a/packages/google-cloud-storage-transfer/setup.py b/packages/google-cloud-storage-transfer/setup.py index a71af64311bb..5b5800c675e5 100644 --- a/packages/google-cloud-storage-transfer/setup.py +++ b/packages/google-cloud-storage-transfer/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-storageinsights/CHANGELOG.md b/packages/google-cloud-storageinsights/CHANGELOG.md index 4177a608dd9d..efe480ac8d48 100644 --- a/packages/google-cloud-storageinsights/CHANGELOG.md +++ b/packages/google-cloud-storageinsights/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-storageinsights-v0.1.7...google-cloud-storageinsights-v0.1.8) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [0.1.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-storageinsights-v0.1.6...google-cloud-storageinsights-v0.1.7) (2024-02-22) diff --git a/packages/google-cloud-storageinsights/google/cloud/storageinsights/gapic_version.py b/packages/google-cloud-storageinsights/google/cloud/storageinsights/gapic_version.py index e34e491c76d0..a59a748f8ebb 100644 --- a/packages/google-cloud-storageinsights/google/cloud/storageinsights/gapic_version.py +++ b/packages/google-cloud-storageinsights/google/cloud/storageinsights/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.7" # {x-release-please-version} +__version__ = "0.1.8" # {x-release-please-version} diff --git a/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/gapic_version.py b/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/gapic_version.py index e34e491c76d0..a59a748f8ebb 100644 --- a/packages/google-cloud-storageinsights/google/cloud/storageinsights_v1/gapic_version.py +++ b/packages/google-cloud-storageinsights/google/cloud/storageinsights_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.7" # {x-release-please-version} +__version__ = "0.1.8" # {x-release-please-version} diff --git a/packages/google-cloud-storageinsights/samples/generated_samples/snippet_metadata_google.cloud.storageinsights.v1.json b/packages/google-cloud-storageinsights/samples/generated_samples/snippet_metadata_google.cloud.storageinsights.v1.json index 7ba58f8a4b13..5cdc7a1632c2 100644 --- a/packages/google-cloud-storageinsights/samples/generated_samples/snippet_metadata_google.cloud.storageinsights.v1.json +++ b/packages/google-cloud-storageinsights/samples/generated_samples/snippet_metadata_google.cloud.storageinsights.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-storageinsights", - "version": "0.1.7" + "version": "0.1.8" }, "snippets": [ { diff --git a/packages/google-cloud-storageinsights/setup.py b/packages/google-cloud-storageinsights/setup.py index 2c82df4f8926..51250525f0c5 100644 --- a/packages/google-cloud-storageinsights/setup.py +++ b/packages/google-cloud-storageinsights/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-support/CHANGELOG.md b/packages/google-cloud-support/CHANGELOG.md index 7d9e175cb76b..bc3149ef3acf 100644 --- a/packages/google-cloud-support/CHANGELOG.md +++ b/packages/google-cloud-support/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.7](https://github.com/googleapis/google-cloud-python/compare/google-cloud-support-v0.1.6...google-cloud-support-v0.1.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [0.1.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-support-v0.1.5...google-cloud-support-v0.1.6) (2024-02-22) diff --git a/packages/google-cloud-support/google/cloud/support/gapic_version.py b/packages/google-cloud-support/google/cloud/support/gapic_version.py index 60402a4567d1..e34e491c76d0 100644 --- a/packages/google-cloud-support/google/cloud/support/gapic_version.py +++ b/packages/google-cloud-support/google/cloud/support/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.6" # {x-release-please-version} +__version__ = "0.1.7" # {x-release-please-version} diff --git a/packages/google-cloud-support/google/cloud/support_v2/gapic_version.py b/packages/google-cloud-support/google/cloud/support_v2/gapic_version.py index 60402a4567d1..e34e491c76d0 100644 --- a/packages/google-cloud-support/google/cloud/support_v2/gapic_version.py +++ b/packages/google-cloud-support/google/cloud/support_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.6" # {x-release-please-version} +__version__ = "0.1.7" # {x-release-please-version} diff --git a/packages/google-cloud-support/samples/generated_samples/snippet_metadata_google.cloud.support.v2.json b/packages/google-cloud-support/samples/generated_samples/snippet_metadata_google.cloud.support.v2.json index 3c251512f2b3..ee23b9a7b184 100644 --- a/packages/google-cloud-support/samples/generated_samples/snippet_metadata_google.cloud.support.v2.json +++ b/packages/google-cloud-support/samples/generated_samples/snippet_metadata_google.cloud.support.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-support", - "version": "0.1.6" + "version": "0.1.7" }, "snippets": [ { diff --git a/packages/google-cloud-support/setup.py b/packages/google-cloud-support/setup.py index 6fb5931a13e4..53ed7b6ecb43 100644 --- a/packages/google-cloud-support/setup.py +++ b/packages/google-cloud-support/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-talent/CHANGELOG.md b/packages/google-cloud-talent/CHANGELOG.md index 2a88147f5322..f7ae4cd2f22d 100644 --- a/packages/google-cloud-talent/CHANGELOG.md +++ b/packages/google-cloud-talent/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-talent/#history +## [2.13.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-talent-v2.13.2...google-cloud-talent-v2.13.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12387](https://github.com/googleapis/google-cloud-python/issues/12387)) ([12ce658](https://github.com/googleapis/google-cloud-python/commit/12ce658210f148eb93d9ff501568fb6f88e77f18)) + ## [2.13.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-talent-v2.13.1...google-cloud-talent-v2.13.2) (2024-02-22) diff --git a/packages/google-cloud-talent/google/cloud/talent/gapic_version.py b/packages/google-cloud-talent/google/cloud/talent/gapic_version.py index d767d5ad8591..6c235a092e73 100644 --- a/packages/google-cloud-talent/google/cloud/talent/gapic_version.py +++ b/packages/google-cloud-talent/google/cloud/talent/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-talent/google/cloud/talent_v4/gapic_version.py b/packages/google-cloud-talent/google/cloud/talent_v4/gapic_version.py index d767d5ad8591..6c235a092e73 100644 --- a/packages/google-cloud-talent/google/cloud/talent_v4/gapic_version.py +++ b/packages/google-cloud-talent/google/cloud/talent_v4/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-talent/google/cloud/talent_v4beta1/gapic_version.py b/packages/google-cloud-talent/google/cloud/talent_v4beta1/gapic_version.py index d767d5ad8591..6c235a092e73 100644 --- a/packages/google-cloud-talent/google/cloud/talent_v4beta1/gapic_version.py +++ b/packages/google-cloud-talent/google/cloud/talent_v4beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-talent/samples/generated_samples/snippet_metadata_google.cloud.talent.v4.json b/packages/google-cloud-talent/samples/generated_samples/snippet_metadata_google.cloud.talent.v4.json index 95edbe2565ef..2846dd617533 100644 --- a/packages/google-cloud-talent/samples/generated_samples/snippet_metadata_google.cloud.talent.v4.json +++ b/packages/google-cloud-talent/samples/generated_samples/snippet_metadata_google.cloud.talent.v4.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-talent", - "version": "2.13.2" + "version": "2.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-talent/samples/generated_samples/snippet_metadata_google.cloud.talent.v4beta1.json b/packages/google-cloud-talent/samples/generated_samples/snippet_metadata_google.cloud.talent.v4beta1.json index 60e65230a3db..fb55ed3eab85 100644 --- a/packages/google-cloud-talent/samples/generated_samples/snippet_metadata_google.cloud.talent.v4beta1.json +++ b/packages/google-cloud-talent/samples/generated_samples/snippet_metadata_google.cloud.talent.v4beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-talent", - "version": "2.13.2" + "version": "2.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-talent/setup.py b/packages/google-cloud-talent/setup.py index 128056bea218..5349873fa84f 100644 --- a/packages/google-cloud-talent/setup.py +++ b/packages/google-cloud-talent/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-tasks/CHANGELOG.md b/packages/google-cloud-tasks/CHANGELOG.md index 9c50c891aecf..0c0082daa794 100644 --- a/packages/google-cloud-tasks/CHANGELOG.md +++ b/packages/google-cloud-tasks/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-tasks/#history +## [2.16.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-tasks-v2.16.2...google-cloud-tasks-v2.16.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [2.16.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-tasks-v2.16.1...google-cloud-tasks-v2.16.2) (2024-02-22) diff --git a/packages/google-cloud-tasks/google/cloud/tasks/gapic_version.py b/packages/google-cloud-tasks/google/cloud/tasks/gapic_version.py index 6d03dad6b6d9..2b7e43322542 100644 --- a/packages/google-cloud-tasks/google/cloud/tasks/gapic_version.py +++ b/packages/google-cloud-tasks/google/cloud/tasks/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.16.2" # {x-release-please-version} +__version__ = "2.16.3" # {x-release-please-version} diff --git a/packages/google-cloud-tasks/google/cloud/tasks_v2/gapic_version.py b/packages/google-cloud-tasks/google/cloud/tasks_v2/gapic_version.py index 6d03dad6b6d9..2b7e43322542 100644 --- a/packages/google-cloud-tasks/google/cloud/tasks_v2/gapic_version.py +++ b/packages/google-cloud-tasks/google/cloud/tasks_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.16.2" # {x-release-please-version} +__version__ = "2.16.3" # {x-release-please-version} diff --git a/packages/google-cloud-tasks/google/cloud/tasks_v2beta2/gapic_version.py b/packages/google-cloud-tasks/google/cloud/tasks_v2beta2/gapic_version.py index 6d03dad6b6d9..2b7e43322542 100644 --- a/packages/google-cloud-tasks/google/cloud/tasks_v2beta2/gapic_version.py +++ b/packages/google-cloud-tasks/google/cloud/tasks_v2beta2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.16.2" # {x-release-please-version} +__version__ = "2.16.3" # {x-release-please-version} diff --git a/packages/google-cloud-tasks/google/cloud/tasks_v2beta3/gapic_version.py b/packages/google-cloud-tasks/google/cloud/tasks_v2beta3/gapic_version.py index 6d03dad6b6d9..2b7e43322542 100644 --- a/packages/google-cloud-tasks/google/cloud/tasks_v2beta3/gapic_version.py +++ b/packages/google-cloud-tasks/google/cloud/tasks_v2beta3/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.16.2" # {x-release-please-version} +__version__ = "2.16.3" # {x-release-please-version} diff --git a/packages/google-cloud-tasks/samples/generated_samples/snippet_metadata_google.cloud.tasks.v2.json b/packages/google-cloud-tasks/samples/generated_samples/snippet_metadata_google.cloud.tasks.v2.json index abddc1700a24..2ca5563d4dfd 100644 --- a/packages/google-cloud-tasks/samples/generated_samples/snippet_metadata_google.cloud.tasks.v2.json +++ b/packages/google-cloud-tasks/samples/generated_samples/snippet_metadata_google.cloud.tasks.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-tasks", - "version": "2.16.2" + "version": "2.16.3" }, "snippets": [ { diff --git a/packages/google-cloud-tasks/samples/generated_samples/snippet_metadata_google.cloud.tasks.v2beta2.json b/packages/google-cloud-tasks/samples/generated_samples/snippet_metadata_google.cloud.tasks.v2beta2.json index b7fb5171f56a..86a96d0e4d1a 100644 --- a/packages/google-cloud-tasks/samples/generated_samples/snippet_metadata_google.cloud.tasks.v2beta2.json +++ b/packages/google-cloud-tasks/samples/generated_samples/snippet_metadata_google.cloud.tasks.v2beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-tasks", - "version": "2.16.2" + "version": "2.16.3" }, "snippets": [ { diff --git a/packages/google-cloud-tasks/samples/generated_samples/snippet_metadata_google.cloud.tasks.v2beta3.json b/packages/google-cloud-tasks/samples/generated_samples/snippet_metadata_google.cloud.tasks.v2beta3.json index 852bfbb80b60..501b6e46c650 100644 --- a/packages/google-cloud-tasks/samples/generated_samples/snippet_metadata_google.cloud.tasks.v2beta3.json +++ b/packages/google-cloud-tasks/samples/generated_samples/snippet_metadata_google.cloud.tasks.v2beta3.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-tasks", - "version": "2.16.2" + "version": "2.16.3" }, "snippets": [ { diff --git a/packages/google-cloud-tasks/setup.py b/packages/google-cloud-tasks/setup.py index 45cc30bcf6e2..c19457ab8c7a 100644 --- a/packages/google-cloud-tasks/setup.py +++ b/packages/google-cloud-tasks/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-telcoautomation/CHANGELOG.md b/packages/google-cloud-telcoautomation/CHANGELOG.md index 49df2dc1649e..a3abedbc81e3 100644 --- a/packages/google-cloud-telcoautomation/CHANGELOG.md +++ b/packages/google-cloud-telcoautomation/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.2.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-telcoautomation-v0.2.2...google-cloud-telcoautomation-v0.2.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [0.2.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-telcoautomation-v0.2.1...google-cloud-telcoautomation-v0.2.2) (2024-02-22) diff --git a/packages/google-cloud-telcoautomation/google/cloud/telcoautomation/gapic_version.py b/packages/google-cloud-telcoautomation/google/cloud/telcoautomation/gapic_version.py index 214aceaa63ce..71423fb2cbb9 100644 --- a/packages/google-cloud-telcoautomation/google/cloud/telcoautomation/gapic_version.py +++ b/packages/google-cloud-telcoautomation/google/cloud/telcoautomation/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.2.2" # {x-release-please-version} +__version__ = "0.2.3" # {x-release-please-version} diff --git a/packages/google-cloud-telcoautomation/google/cloud/telcoautomation_v1/gapic_version.py b/packages/google-cloud-telcoautomation/google/cloud/telcoautomation_v1/gapic_version.py index 214aceaa63ce..71423fb2cbb9 100644 --- a/packages/google-cloud-telcoautomation/google/cloud/telcoautomation_v1/gapic_version.py +++ b/packages/google-cloud-telcoautomation/google/cloud/telcoautomation_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.2" # {x-release-please-version} +__version__ = "0.2.3" # {x-release-please-version} diff --git a/packages/google-cloud-telcoautomation/google/cloud/telcoautomation_v1alpha1/gapic_version.py b/packages/google-cloud-telcoautomation/google/cloud/telcoautomation_v1alpha1/gapic_version.py index 214aceaa63ce..71423fb2cbb9 100644 --- a/packages/google-cloud-telcoautomation/google/cloud/telcoautomation_v1alpha1/gapic_version.py +++ b/packages/google-cloud-telcoautomation/google/cloud/telcoautomation_v1alpha1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.2.2" # {x-release-please-version} +__version__ = "0.2.3" # {x-release-please-version} diff --git a/packages/google-cloud-telcoautomation/samples/generated_samples/snippet_metadata_google.cloud.telcoautomation.v1.json b/packages/google-cloud-telcoautomation/samples/generated_samples/snippet_metadata_google.cloud.telcoautomation.v1.json index a51cd3edab65..36d84fce52ec 100644 --- a/packages/google-cloud-telcoautomation/samples/generated_samples/snippet_metadata_google.cloud.telcoautomation.v1.json +++ b/packages/google-cloud-telcoautomation/samples/generated_samples/snippet_metadata_google.cloud.telcoautomation.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-telcoautomation", - "version": "0.2.2" + "version": "0.2.3" }, "snippets": [ { diff --git a/packages/google-cloud-telcoautomation/samples/generated_samples/snippet_metadata_google.cloud.telcoautomation.v1alpha1.json b/packages/google-cloud-telcoautomation/samples/generated_samples/snippet_metadata_google.cloud.telcoautomation.v1alpha1.json index d95dc76745a3..c5e4d5d98163 100644 --- a/packages/google-cloud-telcoautomation/samples/generated_samples/snippet_metadata_google.cloud.telcoautomation.v1alpha1.json +++ b/packages/google-cloud-telcoautomation/samples/generated_samples/snippet_metadata_google.cloud.telcoautomation.v1alpha1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-telcoautomation", - "version": "0.2.2" + "version": "0.2.3" }, "snippets": [ { diff --git a/packages/google-cloud-telcoautomation/setup.py b/packages/google-cloud-telcoautomation/setup.py index d88b5ef03072..b513c72d5880 100644 --- a/packages/google-cloud-telcoautomation/setup.py +++ b/packages/google-cloud-telcoautomation/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-texttospeech/CHANGELOG.md b/packages/google-cloud-texttospeech/CHANGELOG.md index 0e932499b851..7214ce816fe5 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.16.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-texttospeech-v2.16.2...google-cloud-texttospeech-v2.16.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [2.16.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-texttospeech-v2.16.1...google-cloud-texttospeech-v2.16.2) (2024-02-22) 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 6d03dad6b6d9..2b7e43322542 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.16.2" # {x-release-please-version} +__version__ = "2.16.3" # {x-release-please-version} 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 6d03dad6b6d9..2b7e43322542 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.16.2" # {x-release-please-version} +__version__ = "2.16.3" # {x-release-please-version} 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 6d03dad6b6d9..2b7e43322542 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.16.2" # {x-release-please-version} +__version__ = "2.16.3" # {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 bbd6f95cb4de..9b6158ba8930 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.16.2" + "version": "2.16.3" }, "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 c873e1fd75c1..ae59427218f0 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.16.2" + "version": "2.16.3" }, "snippets": [ { diff --git a/packages/google-cloud-texttospeech/setup.py b/packages/google-cloud-texttospeech/setup.py index 07d7d9d577cd..cf00588934ed 100644 --- a/packages/google-cloud-texttospeech/setup.py +++ b/packages/google-cloud-texttospeech/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-tpu/CHANGELOG.md b/packages/google-cloud-tpu/CHANGELOG.md index 3cf04095f0c4..7d9943442901 100644 --- a/packages/google-cloud-tpu/CHANGELOG.md +++ b/packages/google-cloud-tpu/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.18.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-tpu-v1.18.2...google-cloud-tpu-v1.18.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [1.18.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-tpu-v1.18.1...google-cloud-tpu-v1.18.2) (2024-02-22) diff --git a/packages/google-cloud-tpu/google/cloud/tpu/gapic_version.py b/packages/google-cloud-tpu/google/cloud/tpu/gapic_version.py index 00ba0d9a60cd..07b9890caafb 100644 --- a/packages/google-cloud-tpu/google/cloud/tpu/gapic_version.py +++ b/packages/google-cloud-tpu/google/cloud/tpu/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.18.2" # {x-release-please-version} +__version__ = "1.18.3" # {x-release-please-version} diff --git a/packages/google-cloud-tpu/google/cloud/tpu_v1/gapic_version.py b/packages/google-cloud-tpu/google/cloud/tpu_v1/gapic_version.py index 00ba0d9a60cd..07b9890caafb 100644 --- a/packages/google-cloud-tpu/google/cloud/tpu_v1/gapic_version.py +++ b/packages/google-cloud-tpu/google/cloud/tpu_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.18.2" # {x-release-please-version} +__version__ = "1.18.3" # {x-release-please-version} diff --git a/packages/google-cloud-tpu/google/cloud/tpu_v2/gapic_version.py b/packages/google-cloud-tpu/google/cloud/tpu_v2/gapic_version.py index 00ba0d9a60cd..07b9890caafb 100644 --- a/packages/google-cloud-tpu/google/cloud/tpu_v2/gapic_version.py +++ b/packages/google-cloud-tpu/google/cloud/tpu_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.18.2" # {x-release-please-version} +__version__ = "1.18.3" # {x-release-please-version} diff --git a/packages/google-cloud-tpu/google/cloud/tpu_v2alpha1/gapic_version.py b/packages/google-cloud-tpu/google/cloud/tpu_v2alpha1/gapic_version.py index 00ba0d9a60cd..07b9890caafb 100644 --- a/packages/google-cloud-tpu/google/cloud/tpu_v2alpha1/gapic_version.py +++ b/packages/google-cloud-tpu/google/cloud/tpu_v2alpha1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.18.2" # {x-release-please-version} +__version__ = "1.18.3" # {x-release-please-version} diff --git a/packages/google-cloud-tpu/samples/generated_samples/snippet_metadata_google.cloud.tpu.v1.json b/packages/google-cloud-tpu/samples/generated_samples/snippet_metadata_google.cloud.tpu.v1.json index c5bf24fa2fde..93ac034d6003 100644 --- a/packages/google-cloud-tpu/samples/generated_samples/snippet_metadata_google.cloud.tpu.v1.json +++ b/packages/google-cloud-tpu/samples/generated_samples/snippet_metadata_google.cloud.tpu.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-tpu", - "version": "1.18.2" + "version": "1.18.3" }, "snippets": [ { diff --git a/packages/google-cloud-tpu/samples/generated_samples/snippet_metadata_google.cloud.tpu.v2.json b/packages/google-cloud-tpu/samples/generated_samples/snippet_metadata_google.cloud.tpu.v2.json index b074c22cfa7e..0cc0eca6e4c2 100644 --- a/packages/google-cloud-tpu/samples/generated_samples/snippet_metadata_google.cloud.tpu.v2.json +++ b/packages/google-cloud-tpu/samples/generated_samples/snippet_metadata_google.cloud.tpu.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-tpu", - "version": "1.18.2" + "version": "1.18.3" }, "snippets": [ { diff --git a/packages/google-cloud-tpu/samples/generated_samples/snippet_metadata_google.cloud.tpu.v2alpha1.json b/packages/google-cloud-tpu/samples/generated_samples/snippet_metadata_google.cloud.tpu.v2alpha1.json index 06c8872aae88..6e4baf078cbd 100644 --- a/packages/google-cloud-tpu/samples/generated_samples/snippet_metadata_google.cloud.tpu.v2alpha1.json +++ b/packages/google-cloud-tpu/samples/generated_samples/snippet_metadata_google.cloud.tpu.v2alpha1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-tpu", - "version": "1.18.2" + "version": "1.18.3" }, "snippets": [ { diff --git a/packages/google-cloud-tpu/setup.py b/packages/google-cloud-tpu/setup.py index 8058ea2dae9a..68f885505fe6 100644 --- a/packages/google-cloud-tpu/setup.py +++ b/packages/google-cloud-tpu/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-trace/CHANGELOG.md b/packages/google-cloud-trace/CHANGELOG.md index b29eb9a1116b..1c9a4d55eef0 100644 --- a/packages/google-cloud-trace/CHANGELOG.md +++ b/packages/google-cloud-trace/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-trace/#history +## [1.13.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-trace-v1.13.2...google-cloud-trace-v1.13.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [1.13.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-trace-v1.13.1...google-cloud-trace-v1.13.2) (2024-02-22) diff --git a/packages/google-cloud-trace/google/cloud/trace/gapic_version.py b/packages/google-cloud-trace/google/cloud/trace/gapic_version.py index 3434b217efee..40e034931fac 100644 --- a/packages/google-cloud-trace/google/cloud/trace/gapic_version.py +++ b/packages/google-cloud-trace/google/cloud/trace/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.13.2" # {x-release-please-version} +__version__ = "1.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-trace/google/cloud/trace_v1/gapic_version.py b/packages/google-cloud-trace/google/cloud/trace_v1/gapic_version.py index 3434b217efee..40e034931fac 100644 --- a/packages/google-cloud-trace/google/cloud/trace_v1/gapic_version.py +++ b/packages/google-cloud-trace/google/cloud/trace_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.2" # {x-release-please-version} +__version__ = "1.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-trace/google/cloud/trace_v2/gapic_version.py b/packages/google-cloud-trace/google/cloud/trace_v2/gapic_version.py index 3434b217efee..40e034931fac 100644 --- a/packages/google-cloud-trace/google/cloud/trace_v2/gapic_version.py +++ b/packages/google-cloud-trace/google/cloud/trace_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.2" # {x-release-please-version} +__version__ = "1.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-trace/samples/generated_samples/snippet_metadata_google.devtools.cloudtrace.v1.json b/packages/google-cloud-trace/samples/generated_samples/snippet_metadata_google.devtools.cloudtrace.v1.json index e59244be155d..d6a6e5148442 100644 --- a/packages/google-cloud-trace/samples/generated_samples/snippet_metadata_google.devtools.cloudtrace.v1.json +++ b/packages/google-cloud-trace/samples/generated_samples/snippet_metadata_google.devtools.cloudtrace.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-trace", - "version": "1.13.2" + "version": "1.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-trace/samples/generated_samples/snippet_metadata_google.devtools.cloudtrace.v2.json b/packages/google-cloud-trace/samples/generated_samples/snippet_metadata_google.devtools.cloudtrace.v2.json index 000e000cac45..24fe09d8f9d2 100644 --- a/packages/google-cloud-trace/samples/generated_samples/snippet_metadata_google.devtools.cloudtrace.v2.json +++ b/packages/google-cloud-trace/samples/generated_samples/snippet_metadata_google.devtools.cloudtrace.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-trace", - "version": "1.13.2" + "version": "1.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-trace/setup.py b/packages/google-cloud-trace/setup.py index 27a662faa36b..011e42ad05fa 100644 --- a/packages/google-cloud-trace/setup.py +++ b/packages/google-cloud-trace/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-translate/CHANGELOG.md b/packages/google-cloud-translate/CHANGELOG.md index 5ba7f9b9483e..d39fd0e0397f 100644 --- a/packages/google-cloud-translate/CHANGELOG.md +++ b/packages/google-cloud-translate/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-translate/#history +## [3.15.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-translate-v3.15.2...google-cloud-translate-v3.15.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [3.15.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-translate-v3.15.1...google-cloud-translate-v3.15.2) (2024-02-22) diff --git a/packages/google-cloud-translate/google/cloud/translate/gapic_version.py b/packages/google-cloud-translate/google/cloud/translate/gapic_version.py index dcf8378be674..8a4674fe081d 100644 --- a/packages/google-cloud-translate/google/cloud/translate/gapic_version.py +++ b/packages/google-cloud-translate/google/cloud/translate/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.15.2" # {x-release-please-version} +__version__ = "3.15.3" # {x-release-please-version} diff --git a/packages/google-cloud-translate/google/cloud/translate_v3/gapic_version.py b/packages/google-cloud-translate/google/cloud/translate_v3/gapic_version.py index dcf8378be674..8a4674fe081d 100644 --- a/packages/google-cloud-translate/google/cloud/translate_v3/gapic_version.py +++ b/packages/google-cloud-translate/google/cloud/translate_v3/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.15.2" # {x-release-please-version} +__version__ = "3.15.3" # {x-release-please-version} diff --git a/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic_version.py b/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic_version.py index dcf8378be674..8a4674fe081d 100644 --- a/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic_version.py +++ b/packages/google-cloud-translate/google/cloud/translate_v3beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.15.2" # {x-release-please-version} +__version__ = "3.15.3" # {x-release-please-version} diff --git a/packages/google-cloud-translate/samples/generated_samples/snippet_metadata_google.cloud.translation.v3.json b/packages/google-cloud-translate/samples/generated_samples/snippet_metadata_google.cloud.translation.v3.json index 11b6ed0ccf0a..b39eef16d1d3 100644 --- a/packages/google-cloud-translate/samples/generated_samples/snippet_metadata_google.cloud.translation.v3.json +++ b/packages/google-cloud-translate/samples/generated_samples/snippet_metadata_google.cloud.translation.v3.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-translate", - "version": "3.15.2" + "version": "3.15.3" }, "snippets": [ { diff --git a/packages/google-cloud-translate/samples/generated_samples/snippet_metadata_google.cloud.translation.v3beta1.json b/packages/google-cloud-translate/samples/generated_samples/snippet_metadata_google.cloud.translation.v3beta1.json index a6e51e7ef033..48f6cd6a6a9a 100644 --- a/packages/google-cloud-translate/samples/generated_samples/snippet_metadata_google.cloud.translation.v3beta1.json +++ b/packages/google-cloud-translate/samples/generated_samples/snippet_metadata_google.cloud.translation.v3beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-translate", - "version": "3.15.2" + "version": "3.15.3" }, "snippets": [ { diff --git a/packages/google-cloud-translate/setup.py b/packages/google-cloud-translate/setup.py index d3b2912a3380..c92071dde176 100644 --- a/packages/google-cloud-translate/setup.py +++ b/packages/google-cloud-translate/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "google-cloud-core >= 1.4.4, <3.0.0dev", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", diff --git a/packages/google-cloud-video-live-stream/CHANGELOG.md b/packages/google-cloud-video-live-stream/CHANGELOG.md index 42a4b53eda33..572b540ecb45 100644 --- a/packages/google-cloud-video-live-stream/CHANGELOG.md +++ b/packages/google-cloud-video-live-stream/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.7.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-video-live-stream-v1.7.2...google-cloud-video-live-stream-v1.7.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [1.7.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-video-live-stream-v1.7.1...google-cloud-video-live-stream-v1.7.2) (2024-02-22) diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream/gapic_version.py b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream/gapic_version.py index a71edaad33ab..84f198c2d605 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream/gapic_version.py +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.7.2" # {x-release-please-version} +__version__ = "1.7.3" # {x-release-please-version} diff --git a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/gapic_version.py b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/gapic_version.py index a71edaad33ab..84f198c2d605 100644 --- a/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/gapic_version.py +++ b/packages/google-cloud-video-live-stream/google/cloud/video/live_stream_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.7.2" # {x-release-please-version} +__version__ = "1.7.3" # {x-release-please-version} diff --git a/packages/google-cloud-video-live-stream/samples/generated_samples/snippet_metadata_google.cloud.video.livestream.v1.json b/packages/google-cloud-video-live-stream/samples/generated_samples/snippet_metadata_google.cloud.video.livestream.v1.json index 8bb7e716a715..7ed513e7d809 100644 --- a/packages/google-cloud-video-live-stream/samples/generated_samples/snippet_metadata_google.cloud.video.livestream.v1.json +++ b/packages/google-cloud-video-live-stream/samples/generated_samples/snippet_metadata_google.cloud.video.livestream.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-video-live-stream", - "version": "1.7.2" + "version": "1.7.3" }, "snippets": [ { diff --git a/packages/google-cloud-video-live-stream/setup.py b/packages/google-cloud-video-live-stream/setup.py index 3c81d5eddeff..80f63b2797dd 100644 --- a/packages/google-cloud-video-live-stream/setup.py +++ b/packages/google-cloud-video-live-stream/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-video-stitcher/CHANGELOG.md b/packages/google-cloud-video-stitcher/CHANGELOG.md index f32ac93ccba2..7994fdf44764 100644 --- a/packages/google-cloud-video-stitcher/CHANGELOG.md +++ b/packages/google-cloud-video-stitcher/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.7.9](https://github.com/googleapis/google-cloud-python/compare/google-cloud-video-stitcher-v0.7.8...google-cloud-video-stitcher-v0.7.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [0.7.8](https://github.com/googleapis/google-cloud-python/compare/google-cloud-video-stitcher-v0.7.7...google-cloud-video-stitcher-v0.7.8) (2024-02-22) diff --git a/packages/google-cloud-video-stitcher/google/cloud/video/stitcher/gapic_version.py b/packages/google-cloud-video-stitcher/google/cloud/video/stitcher/gapic_version.py index bb07cd24968f..18c82c15f5f5 100644 --- a/packages/google-cloud-video-stitcher/google/cloud/video/stitcher/gapic_version.py +++ b/packages/google-cloud-video-stitcher/google/cloud/video/stitcher/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.7.8" # {x-release-please-version} +__version__ = "0.7.9" # {x-release-please-version} diff --git a/packages/google-cloud-video-stitcher/google/cloud/video/stitcher_v1/gapic_version.py b/packages/google-cloud-video-stitcher/google/cloud/video/stitcher_v1/gapic_version.py index bb07cd24968f..18c82c15f5f5 100644 --- a/packages/google-cloud-video-stitcher/google/cloud/video/stitcher_v1/gapic_version.py +++ b/packages/google-cloud-video-stitcher/google/cloud/video/stitcher_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.8" # {x-release-please-version} +__version__ = "0.7.9" # {x-release-please-version} diff --git a/packages/google-cloud-video-stitcher/samples/generated_samples/snippet_metadata_google.cloud.video.stitcher.v1.json b/packages/google-cloud-video-stitcher/samples/generated_samples/snippet_metadata_google.cloud.video.stitcher.v1.json index 4d64b7ca5e7a..d0925ae8a8f1 100644 --- a/packages/google-cloud-video-stitcher/samples/generated_samples/snippet_metadata_google.cloud.video.stitcher.v1.json +++ b/packages/google-cloud-video-stitcher/samples/generated_samples/snippet_metadata_google.cloud.video.stitcher.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-video-stitcher", - "version": "0.7.8" + "version": "0.7.9" }, "snippets": [ { diff --git a/packages/google-cloud-video-stitcher/setup.py b/packages/google-cloud-video-stitcher/setup.py index d5bc850b86a4..cdde7a998e76 100644 --- a/packages/google-cloud-video-stitcher/setup.py +++ b/packages/google-cloud-video-stitcher/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-video-transcoder/CHANGELOG.md b/packages/google-cloud-video-transcoder/CHANGELOG.md index 612b8d0ecaaf..cc607b98c3cd 100644 --- a/packages/google-cloud-video-transcoder/CHANGELOG.md +++ b/packages/google-cloud-video-transcoder/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.12.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-video-transcoder-v1.12.2...google-cloud-video-transcoder-v1.12.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [1.12.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-video-transcoder-v1.12.1...google-cloud-video-transcoder-v1.12.2) (2024-02-22) diff --git a/packages/google-cloud-video-transcoder/google/cloud/video/transcoder/gapic_version.py b/packages/google-cloud-video-transcoder/google/cloud/video/transcoder/gapic_version.py index 394a70bae1a3..12049b60eb6c 100644 --- a/packages/google-cloud-video-transcoder/google/cloud/video/transcoder/gapic_version.py +++ b/packages/google-cloud-video-transcoder/google/cloud/video/transcoder/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.12.2" # {x-release-please-version} +__version__ = "1.12.3" # {x-release-please-version} diff --git a/packages/google-cloud-video-transcoder/google/cloud/video/transcoder_v1/gapic_version.py b/packages/google-cloud-video-transcoder/google/cloud/video/transcoder_v1/gapic_version.py index 394a70bae1a3..12049b60eb6c 100644 --- a/packages/google-cloud-video-transcoder/google/cloud/video/transcoder_v1/gapic_version.py +++ b/packages/google-cloud-video-transcoder/google/cloud/video/transcoder_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.2" # {x-release-please-version} +__version__ = "1.12.3" # {x-release-please-version} diff --git a/packages/google-cloud-video-transcoder/samples/generated_samples/snippet_metadata_google.cloud.video.transcoder.v1.json b/packages/google-cloud-video-transcoder/samples/generated_samples/snippet_metadata_google.cloud.video.transcoder.v1.json index 6041a3c08078..33d4940110cd 100644 --- a/packages/google-cloud-video-transcoder/samples/generated_samples/snippet_metadata_google.cloud.video.transcoder.v1.json +++ b/packages/google-cloud-video-transcoder/samples/generated_samples/snippet_metadata_google.cloud.video.transcoder.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-video-transcoder", - "version": "1.12.2" + "version": "1.12.3" }, "snippets": [ { diff --git a/packages/google-cloud-video-transcoder/setup.py b/packages/google-cloud-video-transcoder/setup.py index a8ece53ce21b..008d8c89a38c 100644 --- a/packages/google-cloud-video-transcoder/setup.py +++ b/packages/google-cloud-video-transcoder/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-videointelligence/CHANGELOG.md b/packages/google-cloud-videointelligence/CHANGELOG.md index 832b8f9de782..485aea25af22 100644 --- a/packages/google-cloud-videointelligence/CHANGELOG.md +++ b/packages/google-cloud-videointelligence/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-videointelligence/#history +## [2.13.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-videointelligence-v2.13.2...google-cloud-videointelligence-v2.13.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [2.13.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-videointelligence-v2.13.1...google-cloud-videointelligence-v2.13.2) (2024-02-22) diff --git a/packages/google-cloud-videointelligence/google/cloud/videointelligence/gapic_version.py b/packages/google-cloud-videointelligence/google/cloud/videointelligence/gapic_version.py index d767d5ad8591..6c235a092e73 100644 --- a/packages/google-cloud-videointelligence/google/cloud/videointelligence/gapic_version.py +++ b/packages/google-cloud-videointelligence/google/cloud/videointelligence/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1/gapic_version.py b/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1/gapic_version.py index d767d5ad8591..6c235a092e73 100644 --- a/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1/gapic_version.py +++ b/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1beta2/gapic_version.py b/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1beta2/gapic_version.py index d767d5ad8591..6c235a092e73 100644 --- a/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1beta2/gapic_version.py +++ b/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1beta2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1p1beta1/gapic_version.py b/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1p1beta1/gapic_version.py index d767d5ad8591..6c235a092e73 100644 --- a/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1p1beta1/gapic_version.py +++ b/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1p1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1p2beta1/gapic_version.py b/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1p2beta1/gapic_version.py index d767d5ad8591..6c235a092e73 100644 --- a/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1p2beta1/gapic_version.py +++ b/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1p2beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1p3beta1/gapic_version.py b/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1p3beta1/gapic_version.py index d767d5ad8591..6c235a092e73 100644 --- a/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1p3beta1/gapic_version.py +++ b/packages/google-cloud-videointelligence/google/cloud/videointelligence_v1p3beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.13.2" # {x-release-please-version} +__version__ = "2.13.3" # {x-release-please-version} diff --git a/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1.json b/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1.json index b52374a38c14..42957f54b558 100644 --- a/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1.json +++ b/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-videointelligence", - "version": "2.13.2" + "version": "2.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1beta2.json b/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1beta2.json index 899559a1cce4..cb0ac0f4ba07 100644 --- a/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1beta2.json +++ b/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-videointelligence", - "version": "2.13.2" + "version": "2.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1p1beta1.json b/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1p1beta1.json index ead30c3fce5a..8e34615adc23 100644 --- a/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1p1beta1.json +++ b/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1p1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-videointelligence", - "version": "2.13.2" + "version": "2.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1p2beta1.json b/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1p2beta1.json index 2e8f68794ae1..bdc45d84e9ea 100644 --- a/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1p2beta1.json +++ b/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1p2beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-videointelligence", - "version": "2.13.2" + "version": "2.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1p3beta1.json b/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1p3beta1.json index 79f1528c1dbf..bd5f26943001 100644 --- a/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1p3beta1.json +++ b/packages/google-cloud-videointelligence/samples/generated_samples/snippet_metadata_google.cloud.videointelligence.v1p3beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-videointelligence", - "version": "2.13.2" + "version": "2.13.3" }, "snippets": [ { diff --git a/packages/google-cloud-videointelligence/setup.py b/packages/google-cloud-videointelligence/setup.py index 2104877154de..b1d2ef3514db 100644 --- a/packages/google-cloud-videointelligence/setup.py +++ b/packages/google-cloud-videointelligence/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-vision/CHANGELOG.md b/packages/google-cloud-vision/CHANGELOG.md index d0e800144a38..b95b8b89b940 100644 --- a/packages/google-cloud-vision/CHANGELOG.md +++ b/packages/google-cloud-vision/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-vision/#history +## [3.7.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-vision-v3.7.1...google-cloud-vision-v3.7.2) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [3.7.1](https://github.com/googleapis/google-cloud-python/compare/google-cloud-vision-v3.7.0...google-cloud-vision-v3.7.1) (2024-02-22) diff --git a/packages/google-cloud-vision/google/cloud/vision/gapic_version.py b/packages/google-cloud-vision/google/cloud/vision/gapic_version.py index fa9fb5d574e8..23e540ca8771 100644 --- a/packages/google-cloud-vision/google/cloud/vision/gapic_version.py +++ b/packages/google-cloud-vision/google/cloud/vision/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.7.1" # {x-release-please-version} +__version__ = "3.7.2" # {x-release-please-version} diff --git a/packages/google-cloud-vision/google/cloud/vision_v1/gapic_version.py b/packages/google-cloud-vision/google/cloud/vision_v1/gapic_version.py index fa9fb5d574e8..23e540ca8771 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1/gapic_version.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.7.1" # {x-release-please-version} +__version__ = "3.7.2" # {x-release-please-version} diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/gapic_version.py b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/gapic_version.py index fa9fb5d574e8..23e540ca8771 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/gapic_version.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.7.1" # {x-release-please-version} +__version__ = "3.7.2" # {x-release-please-version} diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/gapic_version.py b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/gapic_version.py index fa9fb5d574e8..23e540ca8771 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/gapic_version.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p2beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.7.1" # {x-release-please-version} +__version__ = "3.7.2" # {x-release-please-version} diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/gapic_version.py b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/gapic_version.py index fa9fb5d574e8..23e540ca8771 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/gapic_version.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p3beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.7.1" # {x-release-please-version} +__version__ = "3.7.2" # {x-release-please-version} diff --git a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/gapic_version.py b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/gapic_version.py index fa9fb5d574e8..23e540ca8771 100644 --- a/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/gapic_version.py +++ b/packages/google-cloud-vision/google/cloud/vision_v1p4beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.7.1" # {x-release-please-version} +__version__ = "3.7.2" # {x-release-please-version} diff --git a/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1.json b/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1.json index a74754b3bf4a..e824429c1f94 100644 --- a/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1.json +++ b/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-vision", - "version": "3.7.1" + "version": "3.7.2" }, "snippets": [ { diff --git a/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p1beta1.json b/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p1beta1.json index 97433837e393..01cb54b6e324 100644 --- a/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p1beta1.json +++ b/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-vision", - "version": "3.7.1" + "version": "3.7.2" }, "snippets": [ { diff --git a/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p2beta1.json b/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p2beta1.json index 2ee11f71b393..d173dafc6759 100644 --- a/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p2beta1.json +++ b/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p2beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-vision", - "version": "3.7.1" + "version": "3.7.2" }, "snippets": [ { diff --git a/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p3beta1.json b/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p3beta1.json index 29c7db5613ae..0adcb6733f41 100644 --- a/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p3beta1.json +++ b/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p3beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-vision", - "version": "3.7.1" + "version": "3.7.2" }, "snippets": [ { diff --git a/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p4beta1.json b/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p4beta1.json index d4c30f96bbff..1c7eb3a45e34 100644 --- a/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p4beta1.json +++ b/packages/google-cloud-vision/samples/generated_samples/snippet_metadata_google.cloud.vision.v1p4beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-vision", - "version": "3.7.1" + "version": "3.7.2" }, "snippets": [ { diff --git a/packages/google-cloud-vision/setup.py b/packages/google-cloud-vision/setup.py index 69156aaf7439..d4600c8426d2 100644 --- a/packages/google-cloud-vision/setup.py +++ b/packages/google-cloud-vision/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-vm-migration/CHANGELOG.md b/packages/google-cloud-vm-migration/CHANGELOG.md index ab6b2d40978e..3100957b9640 100644 --- a/packages/google-cloud-vm-migration/CHANGELOG.md +++ b/packages/google-cloud-vm-migration/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.8.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-vm-migration-v1.8.2...google-cloud-vm-migration-v1.8.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [1.8.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-vm-migration-v1.8.1...google-cloud-vm-migration-v1.8.2) (2024-02-22) diff --git a/packages/google-cloud-vm-migration/google/cloud/vmmigration/gapic_version.py b/packages/google-cloud-vm-migration/google/cloud/vmmigration/gapic_version.py index 0b81cd44c284..f9e85c87b4d6 100644 --- a/packages/google-cloud-vm-migration/google/cloud/vmmigration/gapic_version.py +++ b/packages/google-cloud-vm-migration/google/cloud/vmmigration/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.8.2" # {x-release-please-version} +__version__ = "1.8.3" # {x-release-please-version} diff --git a/packages/google-cloud-vm-migration/google/cloud/vmmigration_v1/gapic_version.py b/packages/google-cloud-vm-migration/google/cloud/vmmigration_v1/gapic_version.py index 0b81cd44c284..f9e85c87b4d6 100644 --- a/packages/google-cloud-vm-migration/google/cloud/vmmigration_v1/gapic_version.py +++ b/packages/google-cloud-vm-migration/google/cloud/vmmigration_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.2" # {x-release-please-version} +__version__ = "1.8.3" # {x-release-please-version} diff --git a/packages/google-cloud-vm-migration/samples/generated_samples/snippet_metadata_google.cloud.vmmigration.v1.json b/packages/google-cloud-vm-migration/samples/generated_samples/snippet_metadata_google.cloud.vmmigration.v1.json index 297eb71d8faa..f31cae376a61 100644 --- a/packages/google-cloud-vm-migration/samples/generated_samples/snippet_metadata_google.cloud.vmmigration.v1.json +++ b/packages/google-cloud-vm-migration/samples/generated_samples/snippet_metadata_google.cloud.vmmigration.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-vm-migration", - "version": "1.8.2" + "version": "1.8.3" }, "snippets": [ { diff --git a/packages/google-cloud-vm-migration/setup.py b/packages/google-cloud-vm-migration/setup.py index 6a1ad8456c62..d71fcdf6270d 100644 --- a/packages/google-cloud-vm-migration/setup.py +++ b/packages/google-cloud-vm-migration/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-vmwareengine/CHANGELOG.md b/packages/google-cloud-vmwareengine/CHANGELOG.md index 9e0fa112542c..4d2b02baacdd 100644 --- a/packages/google-cloud-vmwareengine/CHANGELOG.md +++ b/packages/google-cloud-vmwareengine/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.4.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-vmwareengine-v1.4.2...google-cloud-vmwareengine-v1.4.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [1.4.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-vmwareengine-v1.4.1...google-cloud-vmwareengine-v1.4.2) (2024-02-22) diff --git a/packages/google-cloud-vmwareengine/google/cloud/vmwareengine/gapic_version.py b/packages/google-cloud-vmwareengine/google/cloud/vmwareengine/gapic_version.py index 51f58966561e..4f9b5347cdbf 100644 --- a/packages/google-cloud-vmwareengine/google/cloud/vmwareengine/gapic_version.py +++ b/packages/google-cloud-vmwareengine/google/cloud/vmwareengine/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.4.2" # {x-release-please-version} +__version__ = "1.4.3" # {x-release-please-version} diff --git a/packages/google-cloud-vmwareengine/google/cloud/vmwareengine_v1/gapic_version.py b/packages/google-cloud-vmwareengine/google/cloud/vmwareengine_v1/gapic_version.py index 51f58966561e..4f9b5347cdbf 100644 --- a/packages/google-cloud-vmwareengine/google/cloud/vmwareengine_v1/gapic_version.py +++ b/packages/google-cloud-vmwareengine/google/cloud/vmwareengine_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.4.2" # {x-release-please-version} +__version__ = "1.4.3" # {x-release-please-version} diff --git a/packages/google-cloud-vmwareengine/samples/generated_samples/snippet_metadata_google.cloud.vmwareengine.v1.json b/packages/google-cloud-vmwareengine/samples/generated_samples/snippet_metadata_google.cloud.vmwareengine.v1.json index 3b24bc640fac..23ca830a2e0f 100644 --- a/packages/google-cloud-vmwareengine/samples/generated_samples/snippet_metadata_google.cloud.vmwareengine.v1.json +++ b/packages/google-cloud-vmwareengine/samples/generated_samples/snippet_metadata_google.cloud.vmwareengine.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-vmwareengine", - "version": "1.4.2" + "version": "1.4.3" }, "snippets": [ { diff --git a/packages/google-cloud-vmwareengine/setup.py b/packages/google-cloud-vmwareengine/setup.py index 52234b69377b..caa06e89ac36 100644 --- a/packages/google-cloud-vmwareengine/setup.py +++ b/packages/google-cloud-vmwareengine/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-cloud-vpc-access/CHANGELOG.md b/packages/google-cloud-vpc-access/CHANGELOG.md index d8259d85cbf3..f50307c45158 100644 --- a/packages/google-cloud-vpc-access/CHANGELOG.md +++ b/packages/google-cloud-vpc-access/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.10.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-vpc-access-v1.10.2...google-cloud-vpc-access-v1.10.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [1.10.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-vpc-access-v1.10.1...google-cloud-vpc-access-v1.10.2) (2024-02-22) diff --git a/packages/google-cloud-vpc-access/google/cloud/vpcaccess/gapic_version.py b/packages/google-cloud-vpc-access/google/cloud/vpcaccess/gapic_version.py index 7a033a50e6cd..d74c07c1961e 100644 --- a/packages/google-cloud-vpc-access/google/cloud/vpcaccess/gapic_version.py +++ b/packages/google-cloud-vpc-access/google/cloud/vpcaccess/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.10.2" # {x-release-please-version} +__version__ = "1.10.3" # {x-release-please-version} diff --git a/packages/google-cloud-vpc-access/google/cloud/vpcaccess_v1/gapic_version.py b/packages/google-cloud-vpc-access/google/cloud/vpcaccess_v1/gapic_version.py index 7a033a50e6cd..d74c07c1961e 100644 --- a/packages/google-cloud-vpc-access/google/cloud/vpcaccess_v1/gapic_version.py +++ b/packages/google-cloud-vpc-access/google/cloud/vpcaccess_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.2" # {x-release-please-version} +__version__ = "1.10.3" # {x-release-please-version} diff --git a/packages/google-cloud-vpc-access/samples/generated_samples/snippet_metadata_google.cloud.vpcaccess.v1.json b/packages/google-cloud-vpc-access/samples/generated_samples/snippet_metadata_google.cloud.vpcaccess.v1.json index 124d8fd8b944..0a3b71e4627c 100644 --- a/packages/google-cloud-vpc-access/samples/generated_samples/snippet_metadata_google.cloud.vpcaccess.v1.json +++ b/packages/google-cloud-vpc-access/samples/generated_samples/snippet_metadata_google.cloud.vpcaccess.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-vpc-access", - "version": "1.10.2" + "version": "1.10.3" }, "snippets": [ { diff --git a/packages/google-cloud-vpc-access/setup.py b/packages/google-cloud-vpc-access/setup.py index b647cd306785..bfcf7481ccee 100644 --- a/packages/google-cloud-vpc-access/setup.py +++ b/packages/google-cloud-vpc-access/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-webrisk/CHANGELOG.md b/packages/google-cloud-webrisk/CHANGELOG.md index 0f7126137e2f..8f23f66bec1c 100644 --- a/packages/google-cloud-webrisk/CHANGELOG.md +++ b/packages/google-cloud-webrisk/CHANGELOG.md @@ -3,6 +3,13 @@ [PyPI History][1] [1]: https://pypi.org/project/google-cloud-webrisk/#history +## [1.14.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-webrisk-v1.14.2...google-cloud-webrisk-v1.14.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [1.14.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-webrisk-v1.14.1...google-cloud-webrisk-v1.14.2) (2024-02-22) diff --git a/packages/google-cloud-webrisk/google/cloud/webrisk/gapic_version.py b/packages/google-cloud-webrisk/google/cloud/webrisk/gapic_version.py index 5612fcf86156..616be6a7ff08 100644 --- a/packages/google-cloud-webrisk/google/cloud/webrisk/gapic_version.py +++ b/packages/google-cloud-webrisk/google/cloud/webrisk/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.14.2" # {x-release-please-version} +__version__ = "1.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/gapic_version.py b/packages/google-cloud-webrisk/google/cloud/webrisk_v1/gapic_version.py index 5612fcf86156..616be6a7ff08 100644 --- a/packages/google-cloud-webrisk/google/cloud/webrisk_v1/gapic_version.py +++ b/packages/google-cloud-webrisk/google/cloud/webrisk_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.2" # {x-release-please-version} +__version__ = "1.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-webrisk/google/cloud/webrisk_v1beta1/gapic_version.py b/packages/google-cloud-webrisk/google/cloud/webrisk_v1beta1/gapic_version.py index 5612fcf86156..616be6a7ff08 100644 --- a/packages/google-cloud-webrisk/google/cloud/webrisk_v1beta1/gapic_version.py +++ b/packages/google-cloud-webrisk/google/cloud/webrisk_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.14.2" # {x-release-please-version} +__version__ = "1.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-webrisk/samples/generated_samples/snippet_metadata_google.cloud.webrisk.v1.json b/packages/google-cloud-webrisk/samples/generated_samples/snippet_metadata_google.cloud.webrisk.v1.json index 98c1b5c1b00c..ba9679c51d5d 100644 --- a/packages/google-cloud-webrisk/samples/generated_samples/snippet_metadata_google.cloud.webrisk.v1.json +++ b/packages/google-cloud-webrisk/samples/generated_samples/snippet_metadata_google.cloud.webrisk.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-webrisk", - "version": "1.14.2" + "version": "1.14.3" }, "snippets": [ { diff --git a/packages/google-cloud-webrisk/samples/generated_samples/snippet_metadata_google.cloud.webrisk.v1beta1.json b/packages/google-cloud-webrisk/samples/generated_samples/snippet_metadata_google.cloud.webrisk.v1beta1.json index 9eba69ace8d5..83a7f08cc56b 100644 --- a/packages/google-cloud-webrisk/samples/generated_samples/snippet_metadata_google.cloud.webrisk.v1beta1.json +++ b/packages/google-cloud-webrisk/samples/generated_samples/snippet_metadata_google.cloud.webrisk.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-webrisk", - "version": "1.14.2" + "version": "1.14.3" }, "snippets": [ { diff --git a/packages/google-cloud-webrisk/setup.py b/packages/google-cloud-webrisk/setup.py index 7ae5e84129cd..e54ada99ff71 100644 --- a/packages/google-cloud-webrisk/setup.py +++ b/packages/google-cloud-webrisk/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-websecurityscanner/CHANGELOG.md b/packages/google-cloud-websecurityscanner/CHANGELOG.md index 5f3d60b6856c..af1cbb3e27d8 100644 --- a/packages/google-cloud-websecurityscanner/CHANGELOG.md +++ b/packages/google-cloud-websecurityscanner/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-websecurityscanner/#history +## [1.14.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-websecurityscanner-v1.14.2...google-cloud-websecurityscanner-v1.14.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [1.14.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-websecurityscanner-v1.14.1...google-cloud-websecurityscanner-v1.14.2) (2024-02-22) diff --git a/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner/gapic_version.py b/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner/gapic_version.py index 5612fcf86156..616be6a7ff08 100644 --- a/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner/gapic_version.py +++ b/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.14.2" # {x-release-please-version} +__version__ = "1.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1/gapic_version.py b/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1/gapic_version.py index 5612fcf86156..616be6a7ff08 100644 --- a/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1/gapic_version.py +++ b/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_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.2" # {x-release-please-version} +__version__ = "1.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1alpha/gapic_version.py b/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1alpha/gapic_version.py index 5612fcf86156..616be6a7ff08 100644 --- a/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1alpha/gapic_version.py +++ b/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.14.2" # {x-release-please-version} +__version__ = "1.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1beta/gapic_version.py b/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1beta/gapic_version.py index 5612fcf86156..616be6a7ff08 100644 --- a/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1beta/gapic_version.py +++ b/packages/google-cloud-websecurityscanner/google/cloud/websecurityscanner_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.14.2" # {x-release-please-version} +__version__ = "1.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-websecurityscanner/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1.json b/packages/google-cloud-websecurityscanner/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1.json index ae72bd7a7874..ee8819c45f42 100644 --- a/packages/google-cloud-websecurityscanner/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1.json +++ b/packages/google-cloud-websecurityscanner/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-websecurityscanner", - "version": "1.14.2" + "version": "1.14.3" }, "snippets": [ { diff --git a/packages/google-cloud-websecurityscanner/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1alpha.json b/packages/google-cloud-websecurityscanner/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1alpha.json index 55120f627518..b3654045a4c6 100644 --- a/packages/google-cloud-websecurityscanner/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1alpha.json +++ b/packages/google-cloud-websecurityscanner/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-websecurityscanner", - "version": "1.14.2" + "version": "1.14.3" }, "snippets": [ { diff --git a/packages/google-cloud-websecurityscanner/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1beta.json b/packages/google-cloud-websecurityscanner/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1beta.json index f2f13356d5c7..32b28f92f045 100644 --- a/packages/google-cloud-websecurityscanner/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1beta.json +++ b/packages/google-cloud-websecurityscanner/samples/generated_samples/snippet_metadata_google.cloud.websecurityscanner.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-websecurityscanner", - "version": "1.14.2" + "version": "1.14.3" }, "snippets": [ { diff --git a/packages/google-cloud-websecurityscanner/setup.py b/packages/google-cloud-websecurityscanner/setup.py index a13c54bbfa33..838c6d4f22d4 100644 --- a/packages/google-cloud-websecurityscanner/setup.py +++ b/packages/google-cloud-websecurityscanner/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-workflows/CHANGELOG.md b/packages/google-cloud-workflows/CHANGELOG.md index 023823e3a1d5..d05958a40924 100644 --- a/packages/google-cloud-workflows/CHANGELOG.md +++ b/packages/google-cloud-workflows/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.14.3](https://github.com/googleapis/google-cloud-python/compare/google-cloud-workflows-v1.14.2...google-cloud-workflows-v1.14.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [1.14.2](https://github.com/googleapis/google-cloud-python/compare/google-cloud-workflows-v1.14.1...google-cloud-workflows-v1.14.2) (2024-02-22) diff --git a/packages/google-cloud-workflows/google/cloud/workflows/executions/gapic_version.py b/packages/google-cloud-workflows/google/cloud/workflows/executions/gapic_version.py index 5612fcf86156..616be6a7ff08 100644 --- a/packages/google-cloud-workflows/google/cloud/workflows/executions/gapic_version.py +++ b/packages/google-cloud-workflows/google/cloud/workflows/executions/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.14.2" # {x-release-please-version} +__version__ = "1.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-workflows/google/cloud/workflows/executions_v1/gapic_version.py b/packages/google-cloud-workflows/google/cloud/workflows/executions_v1/gapic_version.py index 5612fcf86156..616be6a7ff08 100644 --- a/packages/google-cloud-workflows/google/cloud/workflows/executions_v1/gapic_version.py +++ b/packages/google-cloud-workflows/google/cloud/workflows/executions_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.2" # {x-release-please-version} +__version__ = "1.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-workflows/google/cloud/workflows/executions_v1beta/gapic_version.py b/packages/google-cloud-workflows/google/cloud/workflows/executions_v1beta/gapic_version.py index 5612fcf86156..616be6a7ff08 100644 --- a/packages/google-cloud-workflows/google/cloud/workflows/executions_v1beta/gapic_version.py +++ b/packages/google-cloud-workflows/google/cloud/workflows/executions_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.14.2" # {x-release-please-version} +__version__ = "1.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-workflows/google/cloud/workflows/gapic_version.py b/packages/google-cloud-workflows/google/cloud/workflows/gapic_version.py index 5612fcf86156..616be6a7ff08 100644 --- a/packages/google-cloud-workflows/google/cloud/workflows/gapic_version.py +++ b/packages/google-cloud-workflows/google/cloud/workflows/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.14.2" # {x-release-please-version} +__version__ = "1.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-workflows/google/cloud/workflows_v1/gapic_version.py b/packages/google-cloud-workflows/google/cloud/workflows_v1/gapic_version.py index 5612fcf86156..616be6a7ff08 100644 --- a/packages/google-cloud-workflows/google/cloud/workflows_v1/gapic_version.py +++ b/packages/google-cloud-workflows/google/cloud/workflows_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.2" # {x-release-please-version} +__version__ = "1.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-workflows/google/cloud/workflows_v1beta/gapic_version.py b/packages/google-cloud-workflows/google/cloud/workflows_v1beta/gapic_version.py index 5612fcf86156..616be6a7ff08 100644 --- a/packages/google-cloud-workflows/google/cloud/workflows_v1beta/gapic_version.py +++ b/packages/google-cloud-workflows/google/cloud/workflows_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.14.2" # {x-release-please-version} +__version__ = "1.14.3" # {x-release-please-version} diff --git a/packages/google-cloud-workflows/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1.json b/packages/google-cloud-workflows/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1.json index ad341ce8a7ba..f4b26dc19704 100644 --- a/packages/google-cloud-workflows/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1.json +++ b/packages/google-cloud-workflows/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-workflows-executions", - "version": "1.14.2" + "version": "1.14.3" }, "snippets": [ { diff --git a/packages/google-cloud-workflows/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1beta.json b/packages/google-cloud-workflows/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1beta.json index a27630965d61..24bafb8d94eb 100644 --- a/packages/google-cloud-workflows/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1beta.json +++ b/packages/google-cloud-workflows/samples/generated_samples/snippet_metadata_google.cloud.workflows.executions.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-workflows-executions", - "version": "1.14.2" + "version": "1.14.3" }, "snippets": [ { diff --git a/packages/google-cloud-workflows/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1.json b/packages/google-cloud-workflows/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1.json index 11f6d466da34..8b8202e54533 100644 --- a/packages/google-cloud-workflows/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1.json +++ b/packages/google-cloud-workflows/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-workflows", - "version": "1.14.2" + "version": "1.14.3" }, "snippets": [ { diff --git a/packages/google-cloud-workflows/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1beta.json b/packages/google-cloud-workflows/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1beta.json index e961ff904a84..ba1c9fd3bbcf 100644 --- a/packages/google-cloud-workflows/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1beta.json +++ b/packages/google-cloud-workflows/samples/generated_samples/snippet_metadata_google.cloud.workflows.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-workflows", - "version": "1.14.2" + "version": "1.14.3" }, "snippets": [ { diff --git a/packages/google-cloud-workflows/setup.py b/packages/google-cloud-workflows/setup.py index 2146e8ddb2d9..a335a2b5ef0a 100644 --- a/packages/google-cloud-workflows/setup.py +++ b/packages/google-cloud-workflows/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-cloud-workstations/CHANGELOG.md b/packages/google-cloud-workstations/CHANGELOG.md index 25bc71c42120..399eae3ae9bf 100644 --- a/packages/google-cloud-workstations/CHANGELOG.md +++ b/packages/google-cloud-workstations/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.5.6](https://github.com/googleapis/google-cloud-python/compare/google-cloud-workstations-v0.5.5...google-cloud-workstations-v0.5.6) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [0.5.5](https://github.com/googleapis/google-cloud-python/compare/google-cloud-workstations-v0.5.4...google-cloud-workstations-v0.5.5) (2024-02-22) diff --git a/packages/google-cloud-workstations/google/cloud/workstations/gapic_version.py b/packages/google-cloud-workstations/google/cloud/workstations/gapic_version.py index 8442537e9014..707b752e07d4 100644 --- a/packages/google-cloud-workstations/google/cloud/workstations/gapic_version.py +++ b/packages/google-cloud-workstations/google/cloud/workstations/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.5" # {x-release-please-version} +__version__ = "0.5.6" # {x-release-please-version} diff --git a/packages/google-cloud-workstations/google/cloud/workstations_v1/gapic_version.py b/packages/google-cloud-workstations/google/cloud/workstations_v1/gapic_version.py index 8442537e9014..707b752e07d4 100644 --- a/packages/google-cloud-workstations/google/cloud/workstations_v1/gapic_version.py +++ b/packages/google-cloud-workstations/google/cloud/workstations_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.5" # {x-release-please-version} +__version__ = "0.5.6" # {x-release-please-version} diff --git a/packages/google-cloud-workstations/google/cloud/workstations_v1beta/gapic_version.py b/packages/google-cloud-workstations/google/cloud/workstations_v1beta/gapic_version.py index 8442537e9014..707b752e07d4 100644 --- a/packages/google-cloud-workstations/google/cloud/workstations_v1beta/gapic_version.py +++ b/packages/google-cloud-workstations/google/cloud/workstations_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.5.5" # {x-release-please-version} +__version__ = "0.5.6" # {x-release-please-version} diff --git a/packages/google-cloud-workstations/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json b/packages/google-cloud-workstations/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json index c714ca6e4e78..4373747e723d 100644 --- a/packages/google-cloud-workstations/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json +++ b/packages/google-cloud-workstations/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-workstations", - "version": "0.5.5" + "version": "0.5.6" }, "snippets": [ { diff --git a/packages/google-cloud-workstations/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json b/packages/google-cloud-workstations/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json index f2c619639c3a..998646c474ed 100644 --- a/packages/google-cloud-workstations/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json +++ b/packages/google-cloud-workstations/samples/generated_samples/snippet_metadata_google.cloud.workstations.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-workstations", - "version": "0.5.5" + "version": "0.5.6" }, "snippets": [ { diff --git a/packages/google-cloud-workstations/setup.py b/packages/google-cloud-workstations/setup.py index 68cd4bb1413f..31ef600cb532 100644 --- a/packages/google-cloud-workstations/setup.py +++ b/packages/google-cloud-workstations/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", diff --git a/packages/google-geo-type/CHANGELOG.md b/packages/google-geo-type/CHANGELOG.md index aff83d59a6fb..7991414b09f3 100644 --- a/packages/google-geo-type/CHANGELOG.md +++ b/packages/google-geo-type/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.3.7](https://github.com/googleapis/google-cloud-python/compare/google-geo-type-v0.3.6...google-geo-type-v0.3.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [0.3.6](https://github.com/googleapis/google-cloud-python/compare/google-geo-type-v0.3.5...google-geo-type-v0.3.6) (2024-02-22) diff --git a/packages/google-geo-type/google/geo/type/gapic_version.py b/packages/google-geo-type/google/geo/type/gapic_version.py index dca6dc837e67..91090a840535 100644 --- a/packages/google-geo-type/google/geo/type/gapic_version.py +++ b/packages/google-geo-type/google/geo/type/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.6" # {x-release-please-version} +__version__ = "0.3.7" # {x-release-please-version} diff --git a/packages/google-geo-type/setup.py b/packages/google-geo-type/setup.py index 15be35765a78..78a0c38044be 100644 --- a/packages/google-geo-type/setup.py +++ b/packages/google-geo-type/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-maps-addressvalidation/CHANGELOG.md b/packages/google-maps-addressvalidation/CHANGELOG.md index 0c4deb0d68ce..3aee71abce64 100644 --- a/packages/google-maps-addressvalidation/CHANGELOG.md +++ b/packages/google-maps-addressvalidation/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.3.11](https://github.com/googleapis/google-cloud-python/compare/google-maps-addressvalidation-v0.3.10...google-maps-addressvalidation-v0.3.11) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12388](https://github.com/googleapis/google-cloud-python/issues/12388)) ([d2cd4ff](https://github.com/googleapis/google-cloud-python/commit/d2cd4ffd12467ad512cccd7a0e9bb897ff2ce2a7)) + ## [0.3.10](https://github.com/googleapis/google-cloud-python/compare/google-maps-addressvalidation-v0.3.9...google-maps-addressvalidation-v0.3.10) (2024-02-22) diff --git a/packages/google-maps-addressvalidation/google/maps/addressvalidation/gapic_version.py b/packages/google-maps-addressvalidation/google/maps/addressvalidation/gapic_version.py index 2373370ae5a0..b55b0fd84971 100644 --- a/packages/google-maps-addressvalidation/google/maps/addressvalidation/gapic_version.py +++ b/packages/google-maps-addressvalidation/google/maps/addressvalidation/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.10" # {x-release-please-version} +__version__ = "0.3.11" # {x-release-please-version} diff --git a/packages/google-maps-addressvalidation/google/maps/addressvalidation_v1/gapic_version.py b/packages/google-maps-addressvalidation/google/maps/addressvalidation_v1/gapic_version.py index 2373370ae5a0..b55b0fd84971 100644 --- a/packages/google-maps-addressvalidation/google/maps/addressvalidation_v1/gapic_version.py +++ b/packages/google-maps-addressvalidation/google/maps/addressvalidation_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.10" # {x-release-please-version} +__version__ = "0.3.11" # {x-release-please-version} diff --git a/packages/google-maps-addressvalidation/samples/generated_samples/snippet_metadata_google.maps.addressvalidation.v1.json b/packages/google-maps-addressvalidation/samples/generated_samples/snippet_metadata_google.maps.addressvalidation.v1.json index 9e7450a1257c..41a93bacda90 100644 --- a/packages/google-maps-addressvalidation/samples/generated_samples/snippet_metadata_google.maps.addressvalidation.v1.json +++ b/packages/google-maps-addressvalidation/samples/generated_samples/snippet_metadata_google.maps.addressvalidation.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-maps-addressvalidation", - "version": "0.3.10" + "version": "0.3.11" }, "snippets": [ { diff --git a/packages/google-maps-addressvalidation/setup.py b/packages/google-maps-addressvalidation/setup.py index 6bd181120e0e..70e1071317f5 100644 --- a/packages/google-maps-addressvalidation/setup.py +++ b/packages/google-maps-addressvalidation/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "google-geo-type >= 0.1.0, <1.0.0dev", diff --git a/packages/google-maps-fleetengine-delivery/CHANGELOG.md b/packages/google-maps-fleetengine-delivery/CHANGELOG.md index 07cc2de457bf..13dc92b0c085 100644 --- a/packages/google-maps-fleetengine-delivery/CHANGELOG.md +++ b/packages/google-maps-fleetengine-delivery/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.7](https://github.com/googleapis/google-cloud-python/compare/google-maps-fleetengine-delivery-v0.1.6...google-maps-fleetengine-delivery-v0.1.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12389](https://github.com/googleapis/google-cloud-python/issues/12389)) ([5db9352](https://github.com/googleapis/google-cloud-python/commit/5db93528a1ad20825d4d12dcf5fdf9624879f2ce)) + ## [0.1.6](https://github.com/googleapis/google-cloud-python/compare/google-maps-fleetengine-delivery-v0.1.5...google-maps-fleetengine-delivery-v0.1.6) (2024-02-22) diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery/gapic_version.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery/gapic_version.py index 60402a4567d1..e34e491c76d0 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery/gapic_version.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.6" # {x-release-please-version} +__version__ = "0.1.7" # {x-release-please-version} diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/gapic_version.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/gapic_version.py index 60402a4567d1..e34e491c76d0 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/gapic_version.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_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.6" # {x-release-please-version} +__version__ = "0.1.7" # {x-release-please-version} diff --git a/packages/google-maps-fleetengine-delivery/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json b/packages/google-maps-fleetengine-delivery/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json index e2ca26add6ca..573c039e1d79 100644 --- a/packages/google-maps-fleetengine-delivery/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json +++ b/packages/google-maps-fleetengine-delivery/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-maps-fleetengine-delivery", - "version": "0.1.6" + "version": "0.1.7" }, "snippets": [ { diff --git a/packages/google-maps-fleetengine-delivery/setup.py b/packages/google-maps-fleetengine-delivery/setup.py index d99fad40f6df..5fa1cfd5992f 100644 --- a/packages/google-maps-fleetengine-delivery/setup.py +++ b/packages/google-maps-fleetengine-delivery/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "google-geo-type >= 0.1.0, <1.0.0dev", diff --git a/packages/google-maps-fleetengine/CHANGELOG.md b/packages/google-maps-fleetengine/CHANGELOG.md index 247f388eaf50..8a3e6bbea5b4 100644 --- a/packages/google-maps-fleetengine/CHANGELOG.md +++ b/packages/google-maps-fleetengine/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.9](https://github.com/googleapis/google-cloud-python/compare/google-maps-fleetengine-v0.1.8...google-maps-fleetengine-v0.1.9) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12389](https://github.com/googleapis/google-cloud-python/issues/12389)) ([5db9352](https://github.com/googleapis/google-cloud-python/commit/5db93528a1ad20825d4d12dcf5fdf9624879f2ce)) + ## [0.1.8](https://github.com/googleapis/google-cloud-python/compare/google-maps-fleetengine-v0.1.7...google-maps-fleetengine-v0.1.8) (2024-02-22) diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine/gapic_version.py b/packages/google-maps-fleetengine/google/maps/fleetengine/gapic_version.py index a59a748f8ebb..bc626a417b8c 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine/gapic_version.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.8" # {x-release-please-version} +__version__ = "0.1.9" # {x-release-please-version} diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/gapic_version.py b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/gapic_version.py index a59a748f8ebb..bc626a417b8c 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/gapic_version.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine_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.8" # {x-release-please-version} +__version__ = "0.1.9" # {x-release-please-version} diff --git a/packages/google-maps-fleetengine/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json b/packages/google-maps-fleetengine/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json index 026f616bd7bb..cffe4282ffb6 100644 --- a/packages/google-maps-fleetengine/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json +++ b/packages/google-maps-fleetengine/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-maps-fleetengine", - "version": "0.1.8" + "version": "0.1.9" }, "snippets": [ { diff --git a/packages/google-maps-fleetengine/setup.py b/packages/google-maps-fleetengine/setup.py index 63cb382c91a5..31db012bebc1 100644 --- a/packages/google-maps-fleetengine/setup.py +++ b/packages/google-maps-fleetengine/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "google-geo-type >= 0.1.0, <1.0.0dev", diff --git a/packages/google-maps-mapsplatformdatasets/CHANGELOG.md b/packages/google-maps-mapsplatformdatasets/CHANGELOG.md index 0f1545782d11..3e7d4e024ede 100644 --- a/packages/google-maps-mapsplatformdatasets/CHANGELOG.md +++ b/packages/google-maps-mapsplatformdatasets/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.3.7](https://github.com/googleapis/google-cloud-python/compare/google-maps-mapsplatformdatasets-v0.3.6...google-maps-mapsplatformdatasets-v0.3.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12389](https://github.com/googleapis/google-cloud-python/issues/12389)) ([5db9352](https://github.com/googleapis/google-cloud-python/commit/5db93528a1ad20825d4d12dcf5fdf9624879f2ce)) + ## [0.3.6](https://github.com/googleapis/google-cloud-python/compare/google-maps-mapsplatformdatasets-v0.3.5...google-maps-mapsplatformdatasets-v0.3.6) (2024-02-22) diff --git a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets/gapic_version.py b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets/gapic_version.py index dca6dc837e67..91090a840535 100644 --- a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets/gapic_version.py +++ b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.6" # {x-release-please-version} +__version__ = "0.3.7" # {x-release-please-version} diff --git a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/gapic_version.py b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/gapic_version.py index dca6dc837e67..91090a840535 100644 --- a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1/gapic_version.py +++ b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_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.6" # {x-release-please-version} +__version__ = "0.3.7" # {x-release-please-version} diff --git a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1alpha/gapic_version.py b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1alpha/gapic_version.py index dca6dc837e67..91090a840535 100644 --- a/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_v1alpha/gapic_version.py +++ b/packages/google-maps-mapsplatformdatasets/google/maps/mapsplatformdatasets_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.6" # {x-release-please-version} +__version__ = "0.3.7" # {x-release-please-version} diff --git a/packages/google-maps-mapsplatformdatasets/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1.json b/packages/google-maps-mapsplatformdatasets/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1.json index 42a201c37762..32d9f7351574 100644 --- a/packages/google-maps-mapsplatformdatasets/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1.json +++ b/packages/google-maps-mapsplatformdatasets/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-maps-mapsplatformdatasets", - "version": "0.3.6" + "version": "0.3.7" }, "snippets": [ { diff --git a/packages/google-maps-mapsplatformdatasets/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1alpha.json b/packages/google-maps-mapsplatformdatasets/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1alpha.json index 5a0c9075484a..c0d5bbc41a25 100644 --- a/packages/google-maps-mapsplatformdatasets/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1alpha.json +++ b/packages/google-maps-mapsplatformdatasets/samples/generated_samples/snippet_metadata_google.maps.mapsplatformdatasets.v1alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-maps-mapsplatformdatasets", - "version": "0.3.6" + "version": "0.3.7" }, "snippets": [ { diff --git a/packages/google-maps-mapsplatformdatasets/setup.py b/packages/google-maps-mapsplatformdatasets/setup.py index 5746d42621db..7c65e62e2786 100644 --- a/packages/google-maps-mapsplatformdatasets/setup.py +++ b/packages/google-maps-mapsplatformdatasets/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/google-maps-places/CHANGELOG.md b/packages/google-maps-places/CHANGELOG.md index 34c817704b81..62c32fcc6a9c 100644 --- a/packages/google-maps-places/CHANGELOG.md +++ b/packages/google-maps-places/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.10](https://github.com/googleapis/google-cloud-python/compare/google-maps-places-v0.1.9...google-maps-places-v0.1.10) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12389](https://github.com/googleapis/google-cloud-python/issues/12389)) ([5db9352](https://github.com/googleapis/google-cloud-python/commit/5db93528a1ad20825d4d12dcf5fdf9624879f2ce)) + ## [0.1.9](https://github.com/googleapis/google-cloud-python/compare/google-maps-places-v0.1.8...google-maps-places-v0.1.9) (2024-02-22) diff --git a/packages/google-maps-places/google/maps/places/gapic_version.py b/packages/google-maps-places/google/maps/places/gapic_version.py index bc626a417b8c..0bb7b8c7c0ef 100644 --- a/packages/google-maps-places/google/maps/places/gapic_version.py +++ b/packages/google-maps-places/google/maps/places/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-maps-places/google/maps/places_v1/gapic_version.py b/packages/google-maps-places/google/maps/places_v1/gapic_version.py index bc626a417b8c..0bb7b8c7c0ef 100644 --- a/packages/google-maps-places/google/maps/places_v1/gapic_version.py +++ b/packages/google-maps-places/google/maps/places_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-maps-places/samples/generated_samples/snippet_metadata_google.maps.places.v1.json b/packages/google-maps-places/samples/generated_samples/snippet_metadata_google.maps.places.v1.json index 763233c172d3..b2cd71958df5 100644 --- a/packages/google-maps-places/samples/generated_samples/snippet_metadata_google.maps.places.v1.json +++ b/packages/google-maps-places/samples/generated_samples/snippet_metadata_google.maps.places.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-maps-places", - "version": "0.1.9" + "version": "0.1.10" }, "snippets": [ { diff --git a/packages/google-maps-places/setup.py b/packages/google-maps-places/setup.py index b5b400b98d27..754d98fc0859 100644 --- a/packages/google-maps-places/setup.py +++ b/packages/google-maps-places/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "google-geo-type >= 0.1.0, <1.0.0dev", diff --git a/packages/google-maps-routing/CHANGELOG.md b/packages/google-maps-routing/CHANGELOG.md index b7f3994c47d3..1c31af96eeab 100644 --- a/packages/google-maps-routing/CHANGELOG.md +++ b/packages/google-maps-routing/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.6.7](https://github.com/googleapis/google-cloud-python/compare/google-maps-routing-v0.6.6...google-maps-routing-v0.6.7) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12389](https://github.com/googleapis/google-cloud-python/issues/12389)) ([5db9352](https://github.com/googleapis/google-cloud-python/commit/5db93528a1ad20825d4d12dcf5fdf9624879f2ce)) + ## [0.6.6](https://github.com/googleapis/google-cloud-python/compare/google-maps-routing-v0.6.5...google-maps-routing-v0.6.6) (2024-02-22) diff --git a/packages/google-maps-routing/google/maps/routing/gapic_version.py b/packages/google-maps-routing/google/maps/routing/gapic_version.py index 31104fb7ab8e..a2a445dd44a2 100644 --- a/packages/google-maps-routing/google/maps/routing/gapic_version.py +++ b/packages/google-maps-routing/google/maps/routing/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.6" # {x-release-please-version} +__version__ = "0.6.7" # {x-release-please-version} diff --git a/packages/google-maps-routing/google/maps/routing_v2/gapic_version.py b/packages/google-maps-routing/google/maps/routing_v2/gapic_version.py index 31104fb7ab8e..a2a445dd44a2 100644 --- a/packages/google-maps-routing/google/maps/routing_v2/gapic_version.py +++ b/packages/google-maps-routing/google/maps/routing_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.6.6" # {x-release-please-version} +__version__ = "0.6.7" # {x-release-please-version} diff --git a/packages/google-maps-routing/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json b/packages/google-maps-routing/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json index 5f446dcab858..ea34b4c6b1ef 100644 --- a/packages/google-maps-routing/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json +++ b/packages/google-maps-routing/samples/generated_samples/snippet_metadata_google.maps.routing.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-maps-routing", - "version": "0.6.6" + "version": "0.6.7" }, "snippets": [ { diff --git a/packages/google-maps-routing/setup.py b/packages/google-maps-routing/setup.py index 209a81bd62bc..cd3cfecadfbb 100644 --- a/packages/google-maps-routing/setup.py +++ b/packages/google-maps-routing/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "google-geo-type >= 0.1.0, <1.0.0dev", diff --git a/packages/google-shopping-css/CHANGELOG.md b/packages/google-shopping-css/CHANGELOG.md index 077aaf7e60f4..18911e0be7b4 100644 --- a/packages/google-shopping-css/CHANGELOG.md +++ b/packages/google-shopping-css/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.4](https://github.com/googleapis/google-cloud-python/compare/google-shopping-css-v0.1.3...google-shopping-css-v0.1.4) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12389](https://github.com/googleapis/google-cloud-python/issues/12389)) ([5db9352](https://github.com/googleapis/google-cloud-python/commit/5db93528a1ad20825d4d12dcf5fdf9624879f2ce)) + ## [0.1.3](https://github.com/googleapis/google-cloud-python/compare/google-shopping-css-v0.1.2...google-shopping-css-v0.1.3) (2024-02-22) diff --git a/packages/google-shopping-css/google/shopping/css/gapic_version.py b/packages/google-shopping-css/google/shopping/css/gapic_version.py index 536d6648a6f0..286ce4ad5531 100644 --- a/packages/google-shopping-css/google/shopping/css/gapic_version.py +++ b/packages/google-shopping-css/google/shopping/css/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-shopping-css/google/shopping/css_v1/gapic_version.py b/packages/google-shopping-css/google/shopping/css_v1/gapic_version.py index 536d6648a6f0..286ce4ad5531 100644 --- a/packages/google-shopping-css/google/shopping/css_v1/gapic_version.py +++ b/packages/google-shopping-css/google/shopping/css_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-shopping-css/samples/generated_samples/snippet_metadata_google.shopping.css.v1.json b/packages/google-shopping-css/samples/generated_samples/snippet_metadata_google.shopping.css.v1.json index e7b8382d99bf..23fb8cd198dd 100644 --- a/packages/google-shopping-css/samples/generated_samples/snippet_metadata_google.shopping.css.v1.json +++ b/packages/google-shopping-css/samples/generated_samples/snippet_metadata_google.shopping.css.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-shopping-css", - "version": "0.1.3" + "version": "0.1.4" }, "snippets": [ { diff --git a/packages/google-shopping-css/setup.py b/packages/google-shopping-css/setup.py index bac25641a9b4..f3f01cbe6ba1 100644 --- a/packages/google-shopping-css/setup.py +++ b/packages/google-shopping-css/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "google-shopping-type >= 0.1.0, <1.0.0dev", diff --git a/packages/google-shopping-merchant-inventories/CHANGELOG.md b/packages/google-shopping-merchant-inventories/CHANGELOG.md index 489992ce40d7..797cd1dbc28c 100644 --- a/packages/google-shopping-merchant-inventories/CHANGELOG.md +++ b/packages/google-shopping-merchant-inventories/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.5](https://github.com/googleapis/google-cloud-python/compare/google-shopping-merchant-inventories-v0.1.4...google-shopping-merchant-inventories-v0.1.5) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12389](https://github.com/googleapis/google-cloud-python/issues/12389)) ([5db9352](https://github.com/googleapis/google-cloud-python/commit/5db93528a1ad20825d4d12dcf5fdf9624879f2ce)) + ## [0.1.4](https://github.com/googleapis/google-cloud-python/compare/google-shopping-merchant-inventories-v0.1.3...google-shopping-merchant-inventories-v0.1.4) (2024-02-22) diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories/gapic_version.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories/gapic_version.py index 286ce4ad5531..ae12f4dfd596 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories/gapic_version.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.1.5" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/gapic_version.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/gapic_version.py index 286ce4ad5531..ae12f4dfd596 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/gapic_version.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.1.5" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-inventories/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json b/packages/google-shopping-merchant-inventories/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json index 573f5350edee..e086e95c1504 100644 --- a/packages/google-shopping-merchant-inventories/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json +++ b/packages/google-shopping-merchant-inventories/samples/generated_samples/snippet_metadata_google.shopping.merchant.inventories.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-shopping-merchant-inventories", - "version": "0.1.4" + "version": "0.1.5" }, "snippets": [ { diff --git a/packages/google-shopping-merchant-inventories/setup.py b/packages/google-shopping-merchant-inventories/setup.py index 3ad3024a6fc3..bfdd53728557 100644 --- a/packages/google-shopping-merchant-inventories/setup.py +++ b/packages/google-shopping-merchant-inventories/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "google-shopping-type >= 0.1.0, <1.0.0dev", diff --git a/packages/google-shopping-merchant-reports/CHANGELOG.md b/packages/google-shopping-merchant-reports/CHANGELOG.md index 7da4d6817dbe..faf85800b381 100644 --- a/packages/google-shopping-merchant-reports/CHANGELOG.md +++ b/packages/google-shopping-merchant-reports/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.5](https://github.com/googleapis/google-cloud-python/compare/google-shopping-merchant-reports-v0.1.4...google-shopping-merchant-reports-v0.1.5) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12389](https://github.com/googleapis/google-cloud-python/issues/12389)) ([5db9352](https://github.com/googleapis/google-cloud-python/commit/5db93528a1ad20825d4d12dcf5fdf9624879f2ce)) + ## [0.1.4](https://github.com/googleapis/google-cloud-python/compare/google-shopping-merchant-reports-v0.1.3...google-shopping-merchant-reports-v0.1.4) (2024-02-22) diff --git a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports/gapic_version.py b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports/gapic_version.py index 286ce4ad5531..ae12f4dfd596 100644 --- a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports/gapic_version.py +++ b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.1.5" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/gapic_version.py b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/gapic_version.py index 286ce4ad5531..ae12f4dfd596 100644 --- a/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/gapic_version.py +++ b/packages/google-shopping-merchant-reports/google/shopping/merchant_reports_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.4" # {x-release-please-version} +__version__ = "0.1.5" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-reports/samples/generated_samples/snippet_metadata_google.shopping.merchant.reports.v1beta.json b/packages/google-shopping-merchant-reports/samples/generated_samples/snippet_metadata_google.shopping.merchant.reports.v1beta.json index 7e4e19ddad91..88b93986bfa9 100644 --- a/packages/google-shopping-merchant-reports/samples/generated_samples/snippet_metadata_google.shopping.merchant.reports.v1beta.json +++ b/packages/google-shopping-merchant-reports/samples/generated_samples/snippet_metadata_google.shopping.merchant.reports.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-shopping-merchant-reports", - "version": "0.1.4" + "version": "0.1.5" }, "snippets": [ { diff --git a/packages/google-shopping-merchant-reports/setup.py b/packages/google-shopping-merchant-reports/setup.py index db212298eedc..26dab089e0ca 100644 --- a/packages/google-shopping-merchant-reports/setup.py +++ b/packages/google-shopping-merchant-reports/setup.py @@ -42,7 +42,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "google-shopping-type >= 0.1.0, <1.0.0dev", diff --git a/packages/google-shopping-type/CHANGELOG.md b/packages/google-shopping-type/CHANGELOG.md index 4e612f5c2c9f..96516a5ec380 100644 --- a/packages/google-shopping-type/CHANGELOG.md +++ b/packages/google-shopping-type/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.4](https://github.com/googleapis/google-cloud-python/compare/google-shopping-type-v0.1.3...google-shopping-type-v0.1.4) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12389](https://github.com/googleapis/google-cloud-python/issues/12389)) ([5db9352](https://github.com/googleapis/google-cloud-python/commit/5db93528a1ad20825d4d12dcf5fdf9624879f2ce)) + ## [0.1.3](https://github.com/googleapis/google-cloud-python/compare/google-shopping-type-v0.1.2...google-shopping-type-v0.1.3) (2024-02-22) diff --git a/packages/google-shopping-type/google/shopping/type/gapic_version.py b/packages/google-shopping-type/google/shopping/type/gapic_version.py index 536d6648a6f0..286ce4ad5531 100644 --- a/packages/google-shopping-type/google/shopping/type/gapic_version.py +++ b/packages/google-shopping-type/google/shopping/type/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-shopping-type/setup.py b/packages/google-shopping-type/setup.py index 5d7552a17b35..119032a21022 100644 --- a/packages/google-shopping-type/setup.py +++ b/packages/google-shopping-type/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/packages/grafeas/CHANGELOG.md b/packages/grafeas/CHANGELOG.md index b37bf4971efb..0be6ff220f3e 100644 --- a/packages/grafeas/CHANGELOG.md +++ b/packages/grafeas/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/grafeas/#history +## [1.9.3](https://github.com/googleapis/google-cloud-python/compare/grafeas-v1.9.2...grafeas-v1.9.3) (2024-03-05) + + +### Bug Fixes + +* **deps:** Exclude google-auth 2.24.0 and 2.25.0 ([#12389](https://github.com/googleapis/google-cloud-python/issues/12389)) ([5db9352](https://github.com/googleapis/google-cloud-python/commit/5db93528a1ad20825d4d12dcf5fdf9624879f2ce)) + ## [1.9.2](https://github.com/googleapis/google-cloud-python/compare/grafeas-v1.9.1...grafeas-v1.9.2) (2024-02-22) diff --git a/packages/grafeas/grafeas/grafeas/gapic_version.py b/packages/grafeas/grafeas/grafeas/gapic_version.py index f14078b6f555..ec42a8e289c4 100644 --- a/packages/grafeas/grafeas/grafeas/gapic_version.py +++ b/packages/grafeas/grafeas/grafeas/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} diff --git a/packages/grafeas/grafeas/grafeas_v1/gapic_version.py b/packages/grafeas/grafeas/grafeas_v1/gapic_version.py index f14078b6f555..ec42a8e289c4 100644 --- a/packages/grafeas/grafeas/grafeas_v1/gapic_version.py +++ b/packages/grafeas/grafeas/grafeas_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.9.2" # {x-release-please-version} +__version__ = "1.9.3" # {x-release-please-version} diff --git a/packages/grafeas/samples/generated_samples/snippet_metadata_grafeas.v1.json b/packages/grafeas/samples/generated_samples/snippet_metadata_grafeas.v1.json index 47cc0861040a..0f530c1476ba 100644 --- a/packages/grafeas/samples/generated_samples/snippet_metadata_grafeas.v1.json +++ b/packages/grafeas/samples/generated_samples/snippet_metadata_grafeas.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "grafeas", - "version": "1.9.2" + "version": "1.9.3" }, "snippets": [ { diff --git a/packages/grafeas/setup.py b/packages/grafeas/setup.py index 65e839d6367c..774196760f94 100644 --- a/packages/grafeas/setup.py +++ b/packages/grafeas/setup.py @@ -40,7 +40,9 @@ dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", ] diff --git a/release-please-config.json b/release-please-config.json index ed598febdf4b..536108d33fcc 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -70,6 +70,31 @@ ], "release-type": "python" }, + "packages/google-apps-card": { + "bump-minor-pre-major": true, + "bump-patch-for-minor-pre-major": true, + "component": "google-apps-card", + "extra-files": [ + "google/apps/card/gapic_version.py", + "google/apps/card_v1/gapic_version.py" + ], + "release-type": "python" + }, + "packages/google-apps-chat": { + "bump-minor-pre-major": true, + "bump-patch-for-minor-pre-major": true, + "component": "google-apps-chat", + "extra-files": [ + "google/apps/chat/gapic_version.py", + "google/apps/chat_v1/gapic_version.py", + { + "jsonpath": "$.clientLibrary.version", + "path": "samples/generated_samples/snippet_metadata_google.chat.v1.json", + "type": "json" + } + ], + "release-type": "python" + }, "packages/google-apps-meet": { "bump-minor-pre-major": true, "bump-patch-for-minor-pre-major": true, @@ -737,6 +762,27 @@ ], "release-type": "python" }, + "packages/google-cloud-cloudcontrolspartner": { + "bump-minor-pre-major": true, + "bump-patch-for-minor-pre-major": true, + "component": "google-cloud-cloudcontrolspartner", + "extra-files": [ + "google/cloud/cloudcontrolspartner/gapic_version.py", + "google/cloud/cloudcontrolspartner_v1/gapic_version.py", + "google/cloud/cloudcontrolspartner_v1beta/gapic_version.py", + { + "jsonpath": "$.clientLibrary.version", + "path": "samples/generated_samples/snippet_metadata_google.cloud.cloudcontrolspartner.v1.json", + "type": "json" + }, + { + "jsonpath": "$.clientLibrary.version", + "path": "samples/generated_samples/snippet_metadata_google.cloud.cloudcontrolspartner.v1beta.json", + "type": "json" + } + ], + "release-type": "python" + }, "packages/google-cloud-cloudquotas": { "bump-minor-pre-major": true, "bump-patch-for-minor-pre-major": true, @@ -1891,6 +1937,21 @@ ], "release-type": "python" }, + "packages/google-cloud-parallelstore": { + "bump-minor-pre-major": true, + "bump-patch-for-minor-pre-major": true, + "component": "google-cloud-parallelstore", + "extra-files": [ + "google/cloud/parallelstore/gapic_version.py", + "google/cloud/parallelstore_v1beta/gapic_version.py", + { + "jsonpath": "$.clientLibrary.version", + "path": "samples/generated_samples/snippet_metadata_google.cloud.parallelstore.v1beta.json", + "type": "json" + } + ], + "release-type": "python" + }, "packages/google-cloud-phishing-protection": { "bump-minor-pre-major": true, "bump-patch-for-minor-pre-major": true, @@ -2248,6 +2309,7 @@ "google/cloud/securitycenter_v1/gapic_version.py", "google/cloud/securitycenter_v1beta1/gapic_version.py", "google/cloud/securitycenter_v1p1beta1/gapic_version.py", + "google/cloud/securitycenter_v2/gapic_version.py", { "jsonpath": "$.clientLibrary.version", "path": "samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1.json", @@ -2262,6 +2324,11 @@ "jsonpath": "$.clientLibrary.version", "path": "samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v1p1beta1.json", "type": "json" + }, + { + "jsonpath": "$.clientLibrary.version", + "path": "samples/generated_samples/snippet_metadata_google.cloud.securitycenter.v2.json", + "type": "json" } ], "release-type": "python" diff --git a/scripts/client-post-processing/add-dependency-google-cloud-common.yaml b/scripts/client-post-processing/add-dependency-google-cloud-common.yaml index 28a44138f7e4..1891abee31e4 100644 --- a/scripts/client-post-processing/add-dependency-google-cloud-common.yaml +++ b/scripts/client-post-processing/add-dependency-google-cloud-common.yaml @@ -20,12 +20,16 @@ replacements: before: | dependencies = \[ "google-api-core\[grpc\] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", after: | dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "google-cloud-common >= 1.0.0, <2.0.0dev", "proto-plus >= 1.22.3, <2.0.0dev", count: 1 diff --git a/scripts/client-post-processing/add-missing-dependencies-to-setup-py-constraints.yaml b/scripts/client-post-processing/add-missing-dependencies-to-setup-py-constraints.yaml index 07d93789c5ad..337f832d91bf 100644 --- a/scripts/client-post-processing/add-missing-dependencies-to-setup-py-constraints.yaml +++ b/scripts/client-post-processing/add-missing-dependencies-to-setup-py-constraints.yaml @@ -20,12 +20,16 @@ replacements: before: | dependencies = \[ "google-api-core\[grpc\] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", after: | dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "grpc-google-iam-v1 >=0.12.4, <1.0.0dev", "proto-plus >= 1.22.3, <2.0.0dev", count: 1 @@ -48,12 +52,16 @@ replacements: before: | dependencies = \[ "google-api-core\[grpc\] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", after: | dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "grpc-google-iam-v1 >=0.12.4, <1.0.0dev", "proto-plus >= 1.22.3, <2.0.0dev", count: 1 @@ -76,12 +84,16 @@ replacements: before: | dependencies = \[ "google-api-core\[grpc\] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", after: | dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "grafeas >= 1.1.2, <2.0dev", "proto-plus >= 1.22.3, <2.0.0dev", count: 1 diff --git a/scripts/client-post-processing/containeranalysis-grafeas-integration.yaml b/scripts/client-post-processing/containeranalysis-grafeas-integration.yaml index 93d44ef6e20b..544a12a13481 100644 --- a/scripts/client-post-processing/containeranalysis-grafeas-integration.yaml +++ b/scripts/client-post-processing/containeranalysis-grafeas-integration.yaml @@ -20,12 +20,16 @@ replacements: before: | dependencies = \[ "google-api-core\[grpc\] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", after: | dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "grafeas >=1.4.1, <2.0dev", "proto-plus >= 1.22.3, <2.0.0dev", count: 1 diff --git a/scripts/client-post-processing/integrate-isolated-handwritten-code.yaml b/scripts/client-post-processing/integrate-isolated-handwritten-code.yaml index 973242a4638c..767f204ddcdd 100644 --- a/scripts/client-post-processing/integrate-isolated-handwritten-code.yaml +++ b/scripts/client-post-processing/integrate-isolated-handwritten-code.yaml @@ -61,12 +61,16 @@ replacements: before: | dependencies = \[ "google-api-core\[grpc\] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", after: | dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "google-cloud-core >= 1.4.4, <3.0.0dev", "proto-plus >= 1.22.3, <2.0.0dev", count: 1 diff --git a/scripts/client-post-processing/mypy-error-with-org-policy-as-dependency.yaml b/scripts/client-post-processing/mypy-error-with-org-policy-as-dependency.yaml index 40db2978f4bf..bd12d26f758c 100644 --- a/scripts/client-post-processing/mypy-error-with-org-policy-as-dependency.yaml +++ b/scripts/client-post-processing/mypy-error-with-org-policy-as-dependency.yaml @@ -20,12 +20,16 @@ replacements: before: | dependencies = \[ "google-api-core\[grpc\] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", after: | dependencies = [ "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "google-auth >= 2.14.1, <3.0.0dev", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "google-cloud-org-policy >= 0.1.2, <2.0.0dev", "proto-plus >= 1.22.3, <2.0.0dev", count: 1